【问题标题】:Cannot access object values from useContext. Using useReducer and useContext for State Management无法从 useContext 访问对象值。使用 useReducer 和 useContext 进行状态管理
【发布时间】:2021-11-10 17:41:19
【问题描述】:

我正在尝试从 useContext 访问我的调度函数以及我的状态。奇怪的是,当我尝试解构上下文对象(因此我可以直接访问它们)时,它告诉我它不存在(错误消息:属性 'authDispatch' 在类型'{}'上不存在)。

解构方法:

 const {authDispatch, authState, messageState, messageDispatch} = useContext(GlobalContext)

但是,当我在不解构的情况下 console.log 上下文时,我能够看到具有相应调度程序/状态的对象。但是,我无法在我的代码中使用点符号访问这些方法/状态。

不解构:

const context = useContext(GlobalContext)

console.log(上下文)

{authState: {…}, messageState: {…}, authDispatch: ƒ, messageDispatch: ƒ}
authDispatch: ƒ ()
authState: {token: null, isAuthenticated: false, loading: true, user: null}
messageDispatch: ƒ ()
messageState: {loadedMessage: {…}, loading: true}
[[Prototype]]: Object

这是我的 Provier.tsx 文件,其中创建了我的 GlobalContext 以及我的 GlobalProvider。 GlobalPrivder 确实包装了整个应用程序。

Provider.tsx

interface IGlobalProvider {
  children: React.ReactNode;
}

export const GlobalContext = createContext({});

export const GlobalProvider: React.FC<IGlobalProvider> = ({ children }) => {
  const [authState, authDispatch] = useReducer(auth, authInitialState);
  const [messageState, messageDispatch] = useReducer(
    todaysMessage,
    todaysMessageInitialState
  );


  return (
    <GlobalContext.Provider
      value={{
        authState,
        authDispatch,
        messageState,
        messageDispatch,
      }}
    >
      {children}
    </GlobalContext.Provider>
  );
};

可能有用的信息:

  • 使用 NextJS

提前感谢您的宝贵时间。

【问题讨论】:

    标签: reactjs typescript next.js use-context use-reducer


    【解决方案1】:

    我只需要在创建上下文时初始化状态

    interface ICreateContext {
      authState: IAuthState | null,
      messageState: ITodaysMessageState | null,
      authDispatch: React.Dispatch<any>,
      messageDispatch: React.Dispatch<any>
    }
    
    const initialState = {
      authState: null,
      messageState: null,
      authDispatch: () => null,
      messageDispatch: () => null
    }
    
    export const GlobalContext = createContext<ICreateContext>(initialState);
    

    但我仍然很好奇为什么我能够 console.log 上下文但在没有初始化的情况下无法访问它们。和渲染周期有关系吗?

    【讨论】:

    • 您的错误只是一个打字稿消息,因为您的上下文类型是{},因为这就是您初始化它的方式。
    猜你喜欢
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多