【问题标题】:How to access data from Context Provider using useContext?如何使用 useContext 从 Context Provider 访问数据?
【发布时间】:2020-08-10 08:12:33
【问题描述】:

如何使用 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 内的任何地方使用 authdata

因为我想从上下文 api 访问密钥和数据

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    您的其他组件需要包装在 Context Provider 中。

    文档:https://pt-br.reactjs.org/docs/hooks-reference.html#usecontext

    【讨论】:

      【解决方案2】:

      为了让你使用 React 的useContexthook,你需要用上下文的提供者包装组件。阅读有关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>
        );
      }
      
      

      【讨论】:

        猜你喜欢
        • 2019-08-07
        • 1970-01-01
        • 2019-07-11
        • 2020-06-13
        • 1970-01-01
        • 1970-01-01
        • 2019-12-21
        • 2019-09-11
        • 2021-04-07
        相关资源
        最近更新 更多