【问题标题】:React-Redux not saving state and always returning initial valuesReact-Redux 不保存状态并始终返回初始值
【发布时间】:2020-03-23 16:47:47
【问题描述】:

在我用 Gatsby 编写的模拟应用程序(无后端)中,我有两个组件显示来自同一对象列表的元素。我的对象是对话线程,因此第一个组件仅显示线程的标题,第二个组件是所有线程中所有消息的长列表。 我希望能够在第一个组件中选择一个线程,以便第二个仅显示属于该线程的对话。 因此,按照我已经在代码的其他部分中使用的模式,我现在拥有以下内容:

reducers.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));
  }
}

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

非常感谢您的帮助。

【问题讨论】:

    标签: reactjs redux state gatsby


    【解决方案1】:

    试试下面的 - 创建现有 redux 状态的副本 - 可用的复制方法很多,你可以使用。

    let newState = JSON.parse(JSON.stringify(state));
    newState.id = action.payload.state.id;
    newState.name = action.payload.state.name;
    return newState;
    

    你也可以使用对象破坏。

    【讨论】:

    • 感谢@user2063635。我已经尝试过了,但这并没有解决我的问题。问题一定出在其他地方,我正试图找出还有什么问题
    【解决方案2】:

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

    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

    【讨论】:

    • 感谢@nicnoniahi。我已经尝试过了,但这并没有解决我的问题。问题一定出在其他地方,我正试图找出还有什么问题。
    猜你喜欢
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    相关资源
    最近更新 更多