【问题标题】:How do i pass a useReducer state using Context? - React Native如何使用 Context 传递 useReducer 状态? - 反应原生
【发布时间】:2021-01-04 22:00:32
【问题描述】:

我有这个 useReducer 状态:

    const initialLoginState = {
    isLoading: true,
    userName: null,
    userToken: null,
    userPassword: null,
    userRegistrado:false,
    };

属于:

const [loginState, dispatch] = React.useReducer(loginReducer, initialLoginState)

我正在传递 2 个上下文(一个带有一些函数的值,以及 StateContext,它是我用来传递 loginState 的那个。

    <AuthContext.Provider value={authContext}>
    <StateContext.Provider value = {loginState}>

      //stacks and drawer
      
    </StateContext.Provider>
    </AuthContext.Provider>

这就是我在注册屏幕中获得价值的方式:

const {loginState} = React.useContext(StateContext);

但是当我尝试从 loginState.userRegistrado 获取值时,我得到了这个错误:

TypeError: 无法读取未定义的属性“userRegistrado”

我正在像这样导入上下文:

从'../../Components/Context'导入{AuthContext, StateContext};

这就是我创建上下文的方式:

    import React from 'react';

export const AuthContext = React.createContext();

export const StateContext = React.createContext();

编辑(我的减速器代码):

      const initialLoginState = {
    isLoading: true,
    userName: null,
    userToken: null,
    userPassword: null,
    userRegistrado:false,
  };
  //funcion del reducer, acepta un estado inicial y una accion
  const loginReducer = (prevState, action) =>{
    switch (action.type){
      //el primer case es para cada vez que el usuario abre la app
      case 'RETRIEVE_TOKEN':
        return{
          ...prevState,
          userToken: action.token,
          isLoading: false,
        };
      case 'LOGIN':
        return{
          ...prevState,
          userName: action.id,
          userToken: action.token,
          isLoading: false,
        };
      case 'LOGOUT':
        return{
          ...prevState,
          userName: null,
          userToken: null,
          isLoading: false,
        };
      case 'REGISTER':
        return{
          ...prevState,
          //userName: action.id,
          //userToken: action.token,
          //userPassword: action.password,
          isLoading: false,
          userRegistrado:true,
        };
    }
  }

  const [loginState, dispatch] = React.useReducer(loginReducer, initialLoginState)

【问题讨论】:

  • 发布你的减速器代码。也许您正在将对象设置为未定义?
  • @JMadelaine 嗨,我刚刚用我的 reducer 代码编辑了它
  • 你需要做类似&lt;AuthContext.Provider value={loginState}&gt;的事情
  • 哈哈不错。我最终创建了沙盒来帮助您:codesandbox.io/s/brave-bhabha-60stj?file=/src/App.js
  • @ShubhamVerma 谢谢!我非常感谢 SO 社区帮助像我这样的新手哈哈! :)

标签: reactjs state


【解决方案1】:

我解决了!我没有在另一个屏幕上调用状态,我调用的是 loginState 对象,但我应该调用状态本身。

我是这样称呼它的:

const {loginState} = React.useContext(StateContext);

当我应该这样称呼它时:

const {userRegistrado} = React.useContext(StateContext);

这是我的灵感来源:link

【讨论】:

    猜你喜欢
    • 2019-03-18
    • 2021-03-23
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多