我有这个路由器,任何应该有布局的页面都包含在withLayout
HOC中。
我需要传递给用户上下文的一些页面,我该如何添加user
道具?
const withLayout = () => Component => props => (
<div css={pageWrap}>
<Header user={props.user} />
<Component {...props} />
</div>
);
export default function Router() {
return (
<AuthConsumer>
{({ user }) => (
<Switch>
<Route exact path="/" component={withLayout()(Home, { user })} />
<Route exact path="/page1" component={withLayout()(Page1)} />
<Route exact path="/page2" component={withLayout()(Page2)} />
</Switch>
)}
</AuthConsumer>
);
}
我认为你的withLayout
有问题。它应该是:
const withLayout = () => (Component, props = {}) => (
<div css={pageWrap}>
<Header user={props.user} />
<Component {...props} />
</div>
);
什么是AuthConsumer?
您可以在页面组件中使用contextType = AuthContext
。 [from]
class MyClass extends React.Component {
static contextType = MyContext;
render() {
let value = this.context;
/* render something based on the value */
}
}
我能够像这样工作:
<Route exact path="/" render={props => withLayout()(Home)({ ...props, user })} />
使用this.props.history.push并传递定义的状态和路由。
this.props.history.push({pathname:'/ yourComponent',State:{valueOrProps:valueWhichisassigning}})
并在this.props.location.state.valueOrProps的下一个组件访问值中。