reactjs - 如何使用 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)
解决方案
我解决了!我没有在另一个屏幕上调用状态,我调用的是 loginState 对象,但我应该调用状态本身。
这就是我所说的:
const {loginState} = React.useContext(StateContext);
当我应该这样称呼它时:
const {userRegistrado} = React.useContext(StateContext);
这就是我从这里得到这个想法的地方:link
推荐阅读
- spring-boot - 如何在 Spring Boot 中使用 JUNIT5 和 mockito 为代码编写 DAO 类的测试用例
- javascript - React 中的 iframe 给出了太多的直接问题
- node.js - 部署heroku时的socket.io错误
- accessibility - 如果网站已经符合 WCAG AA,是否应该显示辅助工具栏?
- ansible - Ansible 解压缩错误/未归档不合适
- sql-server - If 语句不允许插入语句工作,因为单元格为空
- android - 反应本机 - 网络请求仅在 Nougat 上失败
- opengl-es - 哪些函数与 OpenGL / WebGL 中的哪些目标一起使用?
- node.js - 使用 nvm 时 Yarn 版本错误
- c - 我的程序不会停止执行 if 语句但条件不满足