far*_*raz 6 state reactjs redux
我正在使用react和创建一个待办事项列表,redux当我更新redux状态数组时,它不会重新呈现,我的状态实际上是一个包含对象的数组,如下所示:
[{index:1,value:'item1',done:false}, {index:2,value:'item2',done:false}]
我想做的是单击,我想将done的值切换为“ true”,但是以某种方式我无法做到这一点。
这是我在减速器中所做的事情:
list.map((item)=>{
     if(item.index===index){
         item.done=!item.done;
         return [...state,list]
     }
但是,即使单击切换按钮后更改仍然完成,它也不会重新渲染。
看来我在某种程度上改变了状态。请告诉我我要去哪里错了,我应该怎么做。
您能举一些类似的例子吗?我可以正确更新简单数组的状态,但是对包含objects的数组执行此操作会使我感到困惑。所以,你能举个例子吗?
这是完整的reducer代码:
export default function todoApp(state=[],action){
    switch(action.type){
        case 'ADD_TODO':
            return [...state,action.item];
        case 'TOGGLE_TODOS':
            const index = action.index;
            const list = state;
            list.map((item)=>{
            if(item.index===index){
                item.done=!item.done;
            }
            return [...state,list];
            });
        default:
          return state;    
    } 
}
看来我在某种程度上改变了状态。
纠正您正在改变状态,因为在js中,变量总是获取对象/数组的引用。在您的情况下,item将引用数组中的每个对象,并且您直接将的值进行了更改item.done。
另一个问题是您没有正确返回最终对象,还需要为每个映射迭代返回值,否则默认情况下它将返回undefined。
像这样写:
case "TOGGLE_TODOS": 
    return list.map((item) => (
        item.index===index? {...item, done: !item.done}: item
    ))
要么:
case 'TOGGLE_TODOS':
    const index = action.index;
    const newState = [ ...state ];
    newState[index] = { ...state[index], done: !newState[index].done };
    return newState;
完整代码:
export default function todoApp(state=[], action){
    switch(action.type){
        case 'ADD_TODO':
            return [...state, action.item];
        case 'TOGGLE_TODOS':
            const index = action.index;
            return state.map((item) => (
                item.index===index? {...item, done: !item.done}: item
            ))
        default:
            return state;    
    }
}
检查以下代码段:
case "TOGGLE_TODOS": 
    return list.map((item) => (
        item.index===index? {...item, done: !item.done}: item
    ))