【发布时间】:2021-07-29 00:09:04
【问题描述】:
我想达到的目标:
我想更新一个 obj 中的值,它是数组元素的一部分。看下面的代码会给你更好的主意。
有一个问题是我通过引用而不是制作副本来更新对象的值。这会导致状态异常。
我尝试将其更改为制作副本,但我不确定。
例如
const returnObj = {
...objs,
fields: [{name, value}, {name, value}, {name, value_update_this_only}, ...],
};
// This is the current code
export function* onChange(action) {
// get partial state from redux state
const list = yield select((state) => state.list);
let objs = list[action.index];
// * e.g. objs.fields === [{name, value}, {name, value}, ...]
// * basically following, find the correct field and update its value
// * following has problem, beause we change the value of a reference,
// * instead we should make a new copy, so redux can react
objs.fields.map((field) => {
if (field.name === action.fieldName) {
field["value"] = action.fieldValue;
}
return field;
});
// fire to redux reducer
yield put({
type: "UPDATE",
prop: obj,
docIndex: action.index,
});
}
// the problem: I don't know how to do it in destructing manner.
const returnObj = {
...objs,
fields: [],
};
【问题讨论】:
标签: javascript reactjs redux redux-saga self-destruction