简体   繁体   English

如何在Redux中修改对象属性?

[英]How to modify object property in redux?

Trying to create a really simple redux todo, almost there but got stuck on one thing. 试图创建一个非常简单的redux待办事项,几乎在那里,但是卡在了一件事情上。

export const completeTodo = (todo) => ({
  type: 'COMPLETE_TODO',
  data: {
    name: todo,
    complete: !todo.complete
  }
})

however, struggling to get the reducer working as I can't work out how to determine the exact object im working on 但是,由于我无法解决如何确定要在其上工作的确切对象,正在努力使减速器工作

reducer: 减速器:

case 'COMPLETE_TODO': {
   const chore = { ...state.chores, complete: action.data.complete}
   return { ...state.chores, chore };
}

and initialState is: 而initialState是:

const initialState = {
  chores: [{name: 'cleaning', complete: false}]
}

obviously when i click my button is should be wired up so it can change the complete boolean to the opposite but only for that one todo 显然,当我单击我的按钮时,应将其连接起来,以便可以将完整的布尔值更改为相反的值,但仅适用于该一个待办事项

Since you have an array you need to replace it with a new one 由于您拥有一个阵列,因此需要用一个新的阵列替换它

case 'COMPLETE_TODO': {
      return {
        ...state,
        chores: state.chores.map(chore => 
         chore.name === action.data.name
         ? {...chore, complete: true /* or !chore.complete if you want toggle like behaviour*/}
         : chore)
      };
    }

and in your action creator 和你的动作创造者

export const completeTodo = (todo) => ({
  type: 'COMPLETE_TODO',
  data: {
    name: todo.name // assumning names are unique
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM