传递道具反应路由器

时间:2018-06-11 16:59:08

标签: reactjs react-router

我需要通过React Router将道具传递给LawsList组件。所以我想出了这个代码:

在main.js上:

const lawlistcomponent = props => {
  console.log("test");
  return <LawsList {...props} />;
};

const routes = (
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <IndexRoute render={lawlistcomponent} />
      <Route path="laws/:lawId" component={LawsMain} />
      <Route path="votes/:lawId" component={VotesMain} />
    </Route>
  </Router>
);

关于LawsList组件:

 export default createContainer(props => {
  console.log(this.props.voted);
  Meteor.subscribe("laws", props.voted);
  return { laws: Laws.find({}).fetch() };
}, LawsList);

根本不会返回组件。我没有可以指导的错误消息!

任何提示?

1 个答案:

答案 0 :(得分:3)

您的本地lawlistcomponent组件未按照传递给路线的方式接收任何道具。无论如何,我建议您使用render内联函数将组件呈现给路径(假设您使用的是React Router V4)。像这样:

<Route
  exact
  path='/'
  render={(props) => <LawsList {...props} anotherProp={value} />}
/>

如React router docs中所述:

  

这允许方便的内联呈现和包装,而没有上面解释的不期望的重新安装。您可以传入要在位置匹配时调用的函数,而不是使用组件prop为您创建新的React元素。渲染道具接收与组件渲染道具相同的所有路径道具。

感谢您Jens提出建议。

相关问题