首页 > 解决方案 > 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));
  }
}

我已经验证调度调用正在正确执行,但是从第二个组件访问存储的值总是返回初始值。任何想法?我一直在我的代码的其他组件上使用这种相同的模式,所以我真的很困惑并且没有想法。

非常感谢您的帮助。

标签: reactjsreduxstategatsby

解决方案


无法确定数据流是否正确,但我在此处看到错误代码。

switch (action.type) {
    case SET_CONVERSATION: {
      let newstate = action.payload.state;

      return {
        ...state,
        id: newstate.id,
        name: newstate.name
      }
    }

    default:
      return state
  }

您不能直接重新分配值,=因为 Redux 使用不可变数据。这意味着状态只能用新对象替换,不能更改。

有关更多信息,请查看此链接:

https://redux.js.org/introduction/three-principles


推荐阅读