我有以下提供,其中包含身份验证状态。
export const AuthenticationContext = React.createContext();
export default class AuthenticationProvider extends React.Component {
state = {
isAuthenticated: false
};
render() {
return (
<AuthenticationContext.Provider value={{ state: this.state }}>
{this.props.children}
</AuthenticationContext.Provider>
);
}
}
我将其包裹到我的路线中,如下所示:
<Provider store={store}>
<ConnectedRouter history={history}>
<>
<GlobalStyle />
<AuthenticationProvider>
<SiteHeader />
<ErrorWrapper />
<Switch>
<PrivateHomeRoute exact path="/" component={Home} />
<Route exact path="/login" component={LoginPage}
</Switch>
</AuthenticationProvider>
</>
</ConnectedRouter>
</Provider>
但是当我尝试将上下文状态放入<SiteHeader />
时,Context.Provide
并没有传递任何东西。我的消费者在<SiteHeader />
里面是:
class SiteHeader extends React.Component {
render() {
return (
<div>
<AuthenticationContext.Consumer>
{context => (
<header>this is header {context.state.isAuthenticated}</header>
)}
</AuthenticationContext.Consumer>
</div>
);
}
我检查了React devtools,但这是相同的。 Context.Consumer
没有来自value
的{{1}}道具。
答案 0 :(得分:1)
上下文消费者没有获得任何数据作为道具。
相反,我们向他们传递了yourstr.encode('utf-8')
,在这种情况下,我们传递的孩子是render prop函数。然后在Consumer的render方法中发生这种情况
render prop
这就是我们将值作为render prop函数的参数的方式。
不应将上下文提供者的值通过prop传递。您可以了解有关render props here
的更多信息答案 1 :(得分:1)
如果值是false,null或undefined,则它将不会呈现。我在沙盒here中尝试了您的代码。只需在标题中添加.toString(),然后在标题中显示布尔值。