【发布时间】: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