【问题标题】:React/Redux nested state issueReact/Redux 嵌套状态问题
【发布时间】:2018-03-05 04:24:18
【问题描述】:

我是 React/Redux 的新手,我正在尝试将我的一个处于 Redux 状态的对象存储为 Map/Hash,其中键是数据库中对象的主键,值是对象本身。

但是,每次我更新时状态似乎都会被覆盖,而我添加的新值是唯一剩下的值。这是我的代码:

import { RECEIVE_CURRENT_SCAN_RESULT } from '../constants';

const initialState = {
    currentScanResult: {info:{}, results:[]},
};

export default createReducer(initialState, {
    [RECEIVE_CURRENT_SCAN_RESULT]: (state, payload) =>
        Object.assign({}, state, {
            currentScanResult: payload
        })

});


export function createReducer(initialState, reducerMap) {
    return (state = initialState, action) => {
        const reducer = reducerMap[action.type];

        return reducer
            ? reducer(state, action.payload)
            : state;
    }
}

我只想传入我的对象:

{id: 1, thing: "blue"} 

并用它来更新状态。那么如果我传入:

 {id: 2, thing: "red"} 

我希望我的 redux 状态能够反映:

currentScanResult: {1: {id: 1, thing: "blue"}, 2: {id: 2, thing: "red"}}

我有什么简单的方法可以做到这一点吗?如果我要更新嵌套值,redux 会重新渲染吗?例如,如果我传入:

{id: 2, thing: "purple"}

 => currentScanResult: {1: {id: 1, thing: "blue"}, 2: {id: 2, thing: "purple"}}

我希望看到这样的行为。我研究了 Immutable JS 我只是想知道如果没有它我是否可以使这个简单的用例工作?

【问题讨论】:

    标签: reactjs redux react-redux immutable.js


    【解决方案1】:

    当你这样做时

    Object.assign({}, state, {
        currentScanResult: payload
    })
    

    您正在覆盖state.currentScanResult。如果你想更新它,你需要做类似的事情

    Object.assign({}, state, {
        currentScanResult: Object.assign({}, state.currentScanResult, payload)
    })
    

    【讨论】:

    • 谢谢!你知道状态是否会像这样嵌套 redux 时正确更新吗?有什么缺点吗?
    • 没有问题。数据越嵌套,更新内部结构就越繁琐。有关详细信息,请参阅这些文档:redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html
    • 是这种变异状态,由于某种原因,我的组件在更新嵌套值时没有重新渲染...
    • 您可以尝试在reducer中深度复制状态对象以确保检测到更改。 Lodash 有这样一个辅助函数。如果它仍然没有重新渲染,那么你在其他地方有一个错误。如果深拷贝有帮助,请考虑上面评论中的链接 - 或 immutable.js。
    • @JulienD 您仍在使用Object.assign(state.currentScanResult, payload) 更改答案中的状态(或状态中的属性),因为Object.assign 的第一个参数是要修改的目标。所以空对象也需要是该行中的第一个参数:Object.assign({}, state.currentScanResult, payload)
    猜你喜欢
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 2021-11-07
    • 2021-04-15
    • 1970-01-01
    • 2017-05-11
    • 2020-10-26
    • 2017-04-30
    相关资源
    最近更新 更多