【发布时间】: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 代码编辑了它
-
你需要做类似
<AuthContext.Provider value={loginState}>的事情 -
哈哈不错。我最终创建了沙盒来帮助您:codesandbox.io/s/brave-bhabha-60stj?file=/src/App.js
-
@ShubhamVerma 谢谢!我非常感谢 SO 社区帮助像我这样的新手哈哈! :)