因此,我正在努力了解如何更改数组button
中的某些id
iteams.buttons
。我阅读了文档和这篇伟大的帖子How to update single value inside specific array item in redux。但在我的情况下,它没有帮助,因为我还有一些其他错误,我无法抓住。
我做了几个测试,我有什么:
action
通常会将数据发送到reducer
,因为在FORK_TODO
我通过console.log
跟踪它并显示true
(正如我所知)。< / LI>
FORK_TODO
重新呈现后 - 它为我提供了未更改的iteams
数组,但没有对某些state.iteams.buttons.id
进行任何更改,这些更改将更改自己的done
道具相同id
和action.id
。FORK_TODO
重新呈现之后 - 它会破坏我的按钮数组,使其无任何对象,仅使用undefined
数组。所以,我认为构建FORK_TODO
reducer
的问题,但我无法弄清楚...
如果有人在这种情况下看到我的愚蠢错误,请帮忙:(
import { combineReducers } from 'redux'
import { ADD_TODO, FORK_TODO, ADDED_BUTTON, TOGGLE_BUTTON, EDIT_TODO, DELETE_TODO, FILTER_TODO_UP, FILTER_TODO_DOWN } from '../Variables/Variables'
const initialState = {
iteams: {
todos:[],
buttons:[]
}
}
function TodoApp(state, action) {
if (typeof state === 'undefined') {
return initialState;
}
switch (action.type) {
case ADD_TODO:
return Object.assign({}, state, {
iteams: {
todos: [
...state.iteams.todos,
{
id: action.id,
text: action.text,
}
],
buttons: [
...state.iteams.buttons,
{
id: action.id,
text: action.text,
done: 'false'
}
]
}
});
case FORK_TODO:
console.log(state.iteams.buttons[0].id === parseInt(action.id)); // return "true"!!
return {
iteams: {
todos: [
...state.iteams.todos
],
buttons: [
state.iteams.buttons.map(button => {
(button.id === parseInt(action.id))
? {...state.iteams.buttons, done: action.text}
: state.iteams.buttons
})
]
}
}
default:
return state;
}
}
export default TodoApp
UPD : 它现在有效:
case FORK_TODO:
return {
iteams: {
todos: [
...state.iteams.todos
],
buttons: [
...state.iteams.buttons.map(button => {
return (button.id === parseInt(action.id)) ?
{...state.iteams.button, done: !button.done} : button
})
]
}
}
但是!当我们更新某些done
中的button
时,它会重写此obj的所有道具。为什么?在off docs中,这种改变单值的方法只改写this
obj value
,而不是所有的值。
答案 0 :(得分:1)
试试这个:
case FORK_TODO:
console.log(state.iteams.buttons[0].id === parseInt(action.id));
console.log("- action.id -");
console.log(action.id);
console.log(" - state.iteams.buttons[0] - ");
console.log(state.iteams.buttons[0]);
console.log(" - state.iteams - ");
console.log(state.iteams);
const newState = {
iteams: {
todos: [
...state.iteams.todos
],
buttons: [
...state.iteams.buttons.map(button => {
return (button.id === parseInt(action.id)) ?
{...state.iteams.button, done: action.text} : button
})
]
}
}
console.log(" - newState.iteams.buttons[0] - ");
console.log(newState.iteams.buttons[0]);
console.log(" - newState.iteams - ");
console.log(newState.iteams);
return newState;