【问题标题】:How do I pass props to my route component?如何将道具传递给我的路由组件?
【发布时间】:2019-09-11 18:09:18
【问题描述】:

(我是 React Router 初学者,如有任何错误,请原谅我,我的第一个 Stack Overflow 问题。)

我的问题

我有这段代码,我想使用 map 函数从数组(courseData)呈现文章列表,当点击一个时,我想路由到该课程的子页面并呈现一个组件,使用点击文章的id和标题。

我似乎无法理解如何在单击时传递这些道具,因为我对元素了解不多,但我在网上找不到太多信息。

我也想知道放置所有路线的最佳位置是什么。我把一个元素放在一个更高的组件中,里面几乎所有的路线。这是好习惯吗? 我遇到了让我的自定义 404 路由而不是路由显示的错误,因为 404 路由位于更高的组件中。这很容易解决吗?

我尝试通过传递渲染属性而不是组件属性来传递道具,但我无法访问我需要传递的这些道具。

我的代码

const courseData = [
  { id: 1, title: 'Angular - The Complete Guide' },
  { id: 2, title: 'Vue - The Complete Guide' },
  { id: 3, title: 'PWA - The Complete Guide' },
];

const Courses = () => {
  const courses = courseData.map(course => {
    return (
      <Link
        to={'/courses/' + course.id}
        className={style.course}
        key={course.id}
      >
        <article>{course.title}</article>
      </Link>
    );
  });

  return (
    <div>
      <h1>Amazing Udemy Courses</h1>
      <section className={style.courses}>{courses}</section>
      <section />

      <Route exact path='/courses/:id' component={LazyLoad(Course)} />
    </div>
  );
};

LazyLoad 只是一个 HOC,它将传递的组件包装在标签中并传递其 props,因此我可以延迟加载该组件。我已经确认延迟加载不是问题。

如果有人能帮我完成这项工作,那就太棒了。

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    您可以执行以下操作。

    使用组件属性

     <Route exact path='/courses/:id' component={() => <Course someProp={abc}/>}} />
    

    使用渲染道具

    <Route exact path='/courses/:id' render={(props) => <Course someProp={abc} />} />
    

    您可以阅读更多相关信息

    1. https://tylermcginnis.com/react-router-pass-props-to-components/
    2. https://github.com/ReactTraining/react-router/issues/4105

    【讨论】:

    • 组件在问题中被包裹到HOC中。
    • 它会改变答案(语法)吗?
    • 是的,因为现在你必须处理嵌套组件而不是直接传递道具。
    【解决方案2】:

    假设您的 HOC 正确传递收到的道具,这应该可以工作:

    <Route exact path='/courses/:id' component={(routerProps) => LazyLoad(Course)({id: course.id, title: course.title, ...routerProps})} />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 2020-04-07
      • 2015-09-01
      • 2020-03-26
      相关资源
      最近更新 更多