react-native - 更新初始状态后 Redux 状态未更改
问题描述
我有一个带有 redux 和 auth state 和 reducer 的 react native 应用程序
const authState = {
token: 'sample-token',
id: undefined,
username: undefined,
email: undefined,
mobile: undefined
}
const authReducer = (state=authState, action) =>{
switch(action.type){
case "LOGIN":
state = {
...state, token: action.payload.token,
id: action.payload.id, username: action.payload.username,
email: action.payload.email, mobile: action.payload.mobile
};
break;
case "LOGOUT":
state = {
token: '', id: '', username: '', email: '', mobile: ''
};
break;
}
return state;
}
export {authReducer};
最初的 authState 初始状态是:
const authState = {
token: '',
id: '',
username: '',
email: '',
mobile: ''
}
但是,每当我在任何视图中执行 console.log(this.props.auth) 时,我都会得到旧状态的输出,而不是带有新数据的输出。
console.log(this.props.auth)
Output: token: "", id: "", username: "", email: "", mobile: ""}
解决方案
我认为您没有正确导出 authReducer 函数,也没有在 switch 语句中正确返回状态。试试下面的功能,
const authReducer = (state=authState, action) =>{
switch(action.type){
case "LOGIN":
return {
...state, token: action.payload.token,
id: action.payload.id, username: action.payload.username,
email: action.payload.email, mobile: action.payload.mobile
};
case "LOGOUT":
return {
token: '', id: '', username: '', email: '', mobile: ''
};
default:
return state;
}
}
export default authReducer;
推荐阅读
- python - Itertools groupby 按两个值组织字典列表
- angular - 通过 NGC 编译 TypeScript 源错误:超出最大调用堆栈大小 - 如何为 Angular 应用启用调试
- css - Text-Shadow with transparent text color
- node.js - Nodejs:如何读取和遍历ServerResponse?(或者,如何读取客户端 URL 参数?)
- terraform - DestinationAddressPrefix/DestinationAddressPrefixes 的 Azure Terraform NSG 规则创建错误为“AzureMonitor”
- wordpress - 徽标未显示且更改未正确更新
- java - 如何获得价值是选择中的brand.brandName
- kubernetes - 负载测试 kubernetes 服务(使用 istio 服务网格)
- sql - 如何使用 SQL 计算表的频率百分比?
- html - 我是代码新手,为什么我的用户表单没有重定向到相同的链接或没有自动重置表单