【问题标题】:react-router pass previous routes props to sub routereact-router 将先前的路由道具传递给子路由
【发布时间】:2018-07-11 03:31:08
【问题描述】:

有没有办法使用 react-router 将 props 从 Parent 组件传递到 Child 组件?

<Route path="/parent/" component={Parent} />
<Route path="/parent/child/" component={Child} />

注意 Child 没有在 Parent 的渲染函数中渲染。

谢谢

【问题讨论】:

  • 一开始为什么会有这样的层次结构?
  • 也许这是一个愚蠢的想法,但我的组件在父级中呈现的所有子级路由(例如页眉、页脚)中都是一致的。这样它就不必在所有子路由更改时重新渲染。
  • 所以你应该在 Parent 中使用 Route。见stackoverflow.com/questions/41474134/…

标签: reactjs react-router


【解决方案1】:

我认为这里的一个很好的解决方案是使用渲染道具嵌套路由。

// Parent.jsx

render() {
  const { match: { url }, xyz } = this.props;
  return (
    <Route path={`${url}/child`} render={() => <Child xyz={xyz} />}
  );
}

【讨论】:

  • 在您的示例中,我将如何将父状态传递给 组件,以便当父状态更改时 组件将被更新(即它将接收父状态作为道具改变)
  • 因此,除了从 this.props 中提取 xyz 之外,您也可以从 state 中提取任何值并将它们传递给
  • 啊,我实现了一个自定义组件WillUpdate(nextProps, nextState),问题是我的组件在某些情况下没有更新为某些新状态。
猜你喜欢
  • 2015-10-30
  • 1970-01-01
  • 2018-05-19
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-02
相关资源
最近更新 更多