首页 > 解决方案 > 如何使用 Context 传递 useReducer 状态?- 反应原生

问题描述

我有这个 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)

标签: reactjsstate

解决方案


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

这就是我所说的:

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

当我应该这样称呼它时:

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

这就是我从这里得到这个想法的地方:link


推荐阅读