如何使用useContext从Context Provider访问数据 当整个状态传递到值内部时
假设我的状态是这样
const state = {
isAuthenticated: false,
Key: 12345,
data: "Hi"
};
我已经通过提供者在上下文api中传递了此状态
<AuthContext.Provider
value = {{state , dispatch}}
>
</AuthContext.Provider>
现在我正试图通过这种方式在另一个组件中访问它,但是它会引发错误
const { {state.key: auth},{state.data : data} } = useContext(AuthContext)
现在我可以在jsx内的任何地方使用auth
和data
我想从上下文api访问密钥和数据
答案 0 :(得分:0)
您的其他组件需要包装在Context Provider中。
文档:https://pt-br.reactjs.org/docs/hooks-reference.html#usecontext
答案 1 :(得分:0)
为了使用React的useContext
钩子,您需要使用上下文的提供程序包装组件。详细了解Context API。
以下是您的案例示例:
import React from "react";
const AuthContext = React.createContext();
function AuthProvider(props) {
const [state] = React.useState({
isAuthenticated: false,
key: 12345,
data: "Hi",
});
// Any function has to be wrapped in a React.useCallback
// to avoid re-calculation in any dependency array
const dispatch = React.useCallback(() => {}, []); // Redux or useReducer dispatch
// We have to wrap our values in React.useMemo to avoid any unnecessary re-renders
const values = React.useMemo(
() => ({
state,
dispatch,
}),
[dispatch, state]
);
return <AuthContext.Provider value={values} {...props} />;
}
function useAuth() {
const context = React.useContext(AuthContext);
if (!context) {
throw new Error(
"To utilize `useAuth`, component must be wrapped in `AuthProvider`"
);
}
return context;
}
function Component() {
const {
state: { data, key },
} = useAuth();
// ...
}
function App() {
return (
// Everything wrapped in AuthProvider will have access to its values
<AuthProvider>
<Component />
</AuthProvider>
);
}