使用Redux完成TodoList的删除功能
完整代码
src/store/index.js
import { createStore } from 'redux';
import reducer from './reducer';
const store = createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
//如果window存在这个变量,就执行这个变量对应的方法
);
export default store;
src/store/reducer.js
const defaultStore = {
inputValue:'',
list:[]
}
//reducer 可以接受state, 但是绝不能修改state
export default (state = defaultStore, action)=>{
if (action.type === 'change_input_value') {
//对原state进行深拷贝
const newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
return newState
}
if (action.type === "add_todo_item") {
//对原state进行深拷贝
const newState = JSON.parse(JSON.stringify(state));
newState.list = [...newState.list,newState.inputValue]
newState.inputValue = ''
return newState
}
if (action.type === 'remove_todo_item') {
//对原state进行深拷贝
const newState = JSON.parse(JSON.stringify(state));
newState.list.splice(action.index,1)
return newState
}
return state;
}
src/Todulist.js
import React, { Component } from 'react';
import 'antd/dist/antd.css'
import store from './store' //store存储了公用的数据
import {
Input,
Button,
List
} from 'antd';
class TodoList extends Component{
constructor(props){
super(props)
// console.log(store.getState()); 拿到store所有数据
this.state = store.getState();
this.hanldeInputChange = this.hanldeInputChange.bind(this)
this.handleStoreChange = this.handleStoreChange.bind(this)
this.handleButtonClick = this.handleButtonClick.bind(this)
store.subscribe(this.handleStoreChange);
}
render(){
const {inputValue, list} = this.state;
return (
<div style={{marginTop:"10px",marginLeft:'10px'}}>
<Input
value = {inputValue}
placeholder = 'todo info'
style={{width:'300px',marginRight:'10px'}}
onChange = {this.hanldeInputChange}
/>
<Button type='primary' onClick={this.handleButtonClick}>提交</Button>
<List
bordered
dataSource={list}
renderItem={(item,index)=> (
<List.Item onClick={this.handleItemDelete.bind(this,index)}>
{item}
</List.Item>
)}
/>
</div>
)
}
hanldeInputChange(e){
//action的写法也是固定的,它是一个对象
const action = {
type:"change_input_value",
value:e.target.value
}
//把action告诉store后,store会自动把prevStore和action转发给reducer,
//接着我们就可以在reducer中接收到state和action
store.dispatch(action)
}
handleStoreChange(){
// console.log("store changed");
this.setState(store.getState());
}
handleButtonClick(){
//actio是一个对象的样子,有一个type属性
const action = {
type:"add_todo_item"
}
store.dispatch(action)
}
handleItemDelete(index){
const action = {
type:'remove_todo_item',
value: index
}
store.dispatch(action)
}
}
export default TodoList;