[英]using useContext hook get "Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>"
I am using useContext
for my react app, I wrap my parent component with provider and in child component I call useContext to get access to global context and also I use useDispatch
to dispatch the functions within the context.我在我的反应应用程序中使用useContext
,我用提供者包装我的父组件,在子组件中我调用 useContext 来访问全局上下文,并且我使用useDispatch
在上下文中调度函数。
export const QuotesContext = React.createContext<QuoteContextInterface>({});
export const QuotesProvider = QuotesContext.Provider;
const ParentComponent = ({}) => {
return (
<QuotesProvider value={{getUsers, users}} >
<ChildComponent />
</QuotesProvider>
)
}
const ChildComponet = ({}) => {
const quoteContext = useContext(QuotesContext);
const dispatch = useDispatch();
useEffect(() => {
dispatch(quoteContext.getUsers)
}, [])
}
}
the error I get is Error: Uncaught [Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>]
我得到的错误是Error: Uncaught [Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>]
Error: Uncaught [Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>]
also in the error path I see that its is complaining about useDispatch line in child component.同样在错误路径中,我看到它在抱怨子组件中的 useDispatch 行。
I will appreciate your help我会感谢你的帮助
I think you are importing useDispatch
from react-redux
, while context has nothing to do with this.我认为您正在从react-redux
导入useDispatch
,而上下文与此无关。 To change the state of context, your context needs to have it's own state (with useReducer
or useState
).要更改上下文的 state,您的上下文需要有自己的 state(使用useReducer
或useState
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.