gpt4 book ai didi

javascript - 更改所有嵌套对象的值 Immutable.js

转载 作者:行者123 更新时间:2023-11-30 20:50:43 25 4
gpt4 key购买 nike

reducer 看起来像这样

import {ADD_TASK, EDIT_TASK, CHECK_TASK, CHECK_ALL_TASK} from '../constants';
import {OrderedMap, Record} from 'immutable';

const TaskRecord = Record({
id: null,
text: null,
isChecked: false
});

const ReducerState = Record({
entities: new OrderedMap({})
});

const defaultState = new ReducerState();

export default (tasksState = defaultState, action) => {
const {type, payload, randomId} = action;

switch (type) {
case ADD_TASK:
return tasksState.setIn(['entities', randomId], new TaskRecord({...payload.task, id: randomId}));
case CHECK_ALL_TASK:
return tasksState.map(entities => {
return entities.map((task) => {
task.set('isChecked', true);
});
});
};

return tasksState;
};

如何改变实体中TaskRecord中的所有isChecked?我写了 CHECK_ALL_TASK,但它给出了一个错误 (tasksState undefined)

最佳答案

当您想根据当前属性为属性设置新值时,您可以使用 .update。当您想对集合中的每个项目进行更改时,.map 就是您要使用的。在您的情况下,您希望通过修改集合中的每个实体来为属性 entities 设置一个新值。这意味着您要使用 updatemap:

function checkAllBoxes(taskState) {
return taskState.update('entities', entities =>
entities.map(entity =>
entity.set('isChecked', true)));
}

const TaskRecord = Immutable.Record({
id: null,
text: null,
isChecked: false
});

const ReducerState = Immutable.Record({
entities: new Immutable.OrderedMap({})
});

const taskState = new ReducerState({
entities: Immutable.OrderedMap({
a: new TaskRecord(),
b: new TaskRecord(),
c: new TaskRecord()
})
});

function checkAllBoxes(taskState) {
return taskState.update('entities', entities =>
entities.map(entity =>
entity.set('isChecked', true)));
}

console.log(checkAllBoxes(taskState))
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script>

关于javascript - 更改所有嵌套对象的值 Immutable.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48215018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com