删除任务——事件绑定 & action分发 & 数据变更-根据索引删除数组元素-splice(index, 1)
事件绑定;action分发;数据变更
在src/views/List.js中
- 事件绑定
<button data-id={item.id} className="destroy" onClick={deleteTask}></button>
- action分发
import * as Actions from '../store/ActionCreator.js'
function mapDispatchToProps (dispatch) {
return {
deleteTask: (e) => {
// 1、生成一个删除任务的action
let id = e.target.dataset.id
let action = Actions.deleteTaskAction(id)
// 2、分发action
dispatch(action)
}
}
}
在src/store/ActionCreator.js中
/*
ActionCreator 本质上是函数,用于创建Action
Action的本质是一个普通对象
*/
export const addTaskAction = (etitle) => {
return {
type: 'todos_add',
etitle: etitle
}
}
export const deleteTaskAction = (id) => {
return {
type: 'todos_delete',
id: id
}
}
- 数据变更
src/store/Reducer.js
// 删除任务
newState = JSON.parse(JSON.stringify(state))
// 找到要删除的数据索引
let index = newState.todos.findIndex(item => {
return item.id === action.id
})
// 删除数组元素
newState.todos.splice(index, 1)
return newState
删除任务效果