[英]React Context API - One provider, multiple consumers
I am trying to get used to the Context API functionality of React, and what I'm trying to do is to consume the context provided in one component in 2 other components.我正在尝试习惯 React 的 Context API 功能,并且我正在尝试做的是在 2 个其他组件中使用一个组件中提供的上下文。 Unfortunately, when trying to access the context in the second context consumer, the value of the context is undefined
.不幸的是,试图访问第二上下文消费者的上下文时,上下文的值undefined
。 How can I solve this?我该如何解决这个问题?
Provider (snippet)
: Provider (snippet)
:
const [loginState, changeLoginState] = useState({
isAuthenticated: false,
login: () => {}
});
const loginHandler = () => {
let newState = {...loginState};
newState.isAuthenticated = true;
changeLoginState(newState);
};
return (
<div className={CSSmodule.App}>
<AuthContext.Provider value = { {
isAuthenticated: loginState.isAuthenticated,
login: loginHandler
} }>
<Cockpit
showValuesState = {showValuesState}
showContent = {showContent}
personsStateLength = {personsState.length}/>
</AuthContext.Provider>
);
Consumer 1 (works)
: Consumer 1 (works)
:
<AuthContext.Consumer>
{
(context) => {
console.log("[Cockpit.js]", context);
return (
<button
onClick = {context.login}>
Login
</button>
);
}
}
</AuthContext.Consumer>
Consumer 2 (context value is undefined)
: Consumer 2 (context value is undefined)
:
<AuthContext.Consumer>
{
(context) => {
console.log("[from Person.js]", context);
if(context.isAuthenticated)
return (<p>Authenticated!</p>);
}
}
</AuthContext.Consumer>
Imported AuthContext component from context.js
: Imported AuthContext component from context.js
:
import React from "react";
const context = React.createContext();
export default context;
The way context sharing works is that all your components which needs to access the context data must be wrapped within a single provider.上下文共享的工作方式是所有需要访问上下文数据的组件都必须包装在单个提供程序中。
<Context.Provider value={}>
<App/>
</Context.Provider>
In the above snippet, App
is the top most component.在上面的代码片段中, App
是最顶层的组件。 The hierarchy is:层次结构是:
App
|-- Home
|-- About
Now Home
and About
can access values from the Context.现在Home
和About
可以访问 Context 中的值。
In your code, Person.js
is probably not rendered as a descendant of the <AuthContext.Provider>
, so it can't get access to it.在您的代码中, Person.js
可能没有呈现为<AuthContext.Provider>
的后代,因此它无法访问它。 In other words, the provider should "enclose" the consumers.换句话说,提供者应该“包围”消费者。 From the docs :从文档:
Context is designed to share data that can be considered “global” for a tree of React components [...] Context 旨在共享可被视为“全局”的 React 组件树的数据 [...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.