将用户prop传递给所有子router



我想写一个包装器组件来传递任何子道具。例如在纯反应认证系统中。

<Router history={ hashHistory } >
<Route path="/" component={Base}>
<Route component={Auth}>
    <Route path="/who" component={Who} />
    <Route path="/features" component={Features} />
    <Route path="/try" component={Try} />
</Route>
</Route>
</Router>

我想通过props将用户传递给Auth中的Who、Features或Try组件,这些组件将从本地存储中提取。

我试图做的愚蠢的事情是操纵它。Props或者this。Props。children但这不行,推荐的解决方案是什么?

class Auth extends Component {
  render() {
    //find user or null
    var user = JSON.parse(localStorage.getItem('user')) || [];
    //this.props.user = user;
    console.log('top level router props.user', this.props.user);
    return (
    <div>
    {this.props.children}
    </div>
    );
  }
}

查看Jess的回答。React clone元素就是你想要的。

React router和this.props.children -如何将状态传递给this.props.children

render() {
    var childrenWithProps = React.cloneElement(this.props.children, {someProp: this.state.someProp});
    return (
      <div>
        <Header />
        {childrenWithProps}
      </div>
    );
  }

如果您升级到版本4,您可以使用Match与您自己的HOC进行验证。

https://react-router.now.sh/auth-workflow

最新更新