[英]pass user prop to all children react router
I want to write a wrapper component that passes any children props. 我想编写一个传递所有子道具的包装器组件。 For example in a pure react auth system.
例如,在纯React身份验证系统中。
<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>
I want to pass a user by props to either the Who, Features or Try components from Auth, which will pull from local storage. 我想通过道具将用户传递给Auth的Who,Features或Try组件,后者将从本地存储中提取。
The silly thing I have tried to do is to manipulate this.props or this.props.children but this is not ok, what is the recommended solution? 我试图做的愚蠢的事情是操纵this.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>
);
}
}
see this answer by Jess. 看到杰西的答案。 React clone element is what you want.
React clone元素就是您想要的。
React router and this.props.children - how to pass state to this.props.children 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>
);
}
If you upgrade to version 4 you can use Match with your own HOC for auth. 如果您升级到版本4,则可以将Match与您自己的HOC结合使用以进行身份验证。
https://react-router.now.sh/auth-workflow https://react-router.now.sh/auth-workflow
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.