reactjs - React-Redux 不保存状态并始终返回初始值
问题描述
在我用 Gatsby 编写的模拟应用程序(无后端)中,我有两个组件显示来自同一对象列表的元素。我的对象是对话线程,因此第一个组件仅显示线程的标题,第二个组件是所有线程中所有消息的长列表。我希望能够在第一个组件中选择一个线程,以便第二个仅显示属于该线程的对话。因此,按照我已经在代码的其他部分中使用的模式,我现在拥有以下内容:
减速器.js
...
const activeConversation = (state = {id : -1, name: "none"}, action) => {
switch (action.type) {
case SET_CONVERSATION:
//I have tried all possible variations I could think of the following
let newstate = action.payload.state;
state.id = newstate.id;
state.name = newstate.name;
//also tried to directly return action.payload.state and state
return newstate;
default:
return state
}
}
...
const rootReducer = combineReducers({activeConversation, /*more here*/})
export default rootReducer;
我的动作定义为:
import {SET_CONVERSATION} from "./preferences";
export default function setConversation(state){
return {
type: SET_CONVERSATION,
payload: {
state
}
}
}
我正在发送以下内容:
let [conversation, saveConversation] = React.useState("0");
const setConversation = (event) => {
saveConversation(event.currentTarget.id);
let selected = {
id: conversation,
name: toString(conversation)
}
props.dispatch(actionSetConversation(selected));
}
}
我已经验证调度调用正在正确执行,但是从第二个组件访问存储的值总是返回初始值。任何想法?我一直在我的代码的其他组件上使用这种相同的模式,所以我真的很困惑并且没有想法。
非常感谢您的帮助。
解决方案
无法确定数据流是否正确,但我在此处看到错误代码。
switch (action.type) {
case SET_CONVERSATION: {
let newstate = action.payload.state;
return {
...state,
id: newstate.id,
name: newstate.name
}
}
default:
return state
}
您不能直接重新分配值,=
因为 Redux 使用不可变数据。这意味着状态只能用新对象替换,不能更改。
有关更多信息,请查看此链接:
推荐阅读
- python - python电子邮件脚本循环错误想知道每次迭代
- python - 协方差矩阵返回不同的值
- html - 在零宽度元素中居中文本
- rasa - 用实体列表填充槽 | 拉萨
- python - 为什么我不能在“return”语句中使用 exec()
- visual-studio-2019 - 无法从 Visual Studio 2019 16.6.2 调试 Blazor 托管的 webassembly 3.2.0
- laravel - 验证数组 - 获取当前迭代
- sql - 使用带有多个表和连接的 Group By 进行 SQL 计数
- html - 滚动时上方的 Mat-Table 重叠菜单
- snakemake - 在云存储桶中指定文件路径的最低要求