Skip to main content

使用Redux完成TodoList的删除功能

现在我们有个需求:点击item的时候,item会被自动删除

实现:我们需要将item的index传入

  const deleteItem = (index) => {
const action = {
type:'delete_item_action',
index
}
store.dispatch(action)
}

对应的dom:

    <List
bordered
dataSource={list}
renderItem={(item,index) => (
<List.Item onClick={()=>deleteItem(index)}>
{item}
</List.Item>
)}
style={{width:'300px',marginTop:'10px'}}
/>

reducer:

const defaultState = {
inputValue:'',
list:['1','2']
}

//reducer本质就是一个函数
const reducer = (state=defaultState, action) => {
//对state进行深拷贝
const newState = JSON.parse(JSON.stringify(state))
switch (action.type) {
case 'change_inputvalue_action':
newState.inputValue = action.value
return newState
case 'add_item_action':
newState.list.push(action.data)
newState.inputValue = ''
//清空inputValue
return newState
case 'delete_item_action':
newState.list.splice(action.index,1)
return newState
default:
break;
}
return state
}

export default reducer