目前ToDoList组件里有很多Action,并且分散在程序的各个地方,如果庞大的工程,这势必会造成混乱,那么接下来把所有的Redux Action放在一个文件里进行管理
新建文件actionCreators.js
import {DELETE_ITEM,CHANGE_INPUT,ADD_ITEM} from '../actionTypes'
export const changeInputAction=(value)=>({
type:CHANGE_INPUT,
value
})
export const deleteItemAction=(value)=>({
type:DELETE_ITEM,
value
})
export const addItemAction=()=>({
type:ADD_ITEM
})
ToDoList.js
import React, { Component } from 'react';
import 'antd/dist/antd.css'
import {Input,Button,List } from 'antd'
import store from './store/store'
// import {DELETE_ITEM,CHANGE_INPUT,ADD_ITEM} from './actionTypes'
import {changeInputAction,deleteItemAction,addItemAction} from './store/actionCreators'
// const data=[
// '跑跑卡丁车',
// '穿越火线',
// '真三国无双'
// ]
class ToDoList extends Component {
constructor(props) {
super(props);
this.state = store.getState();
this.storeChange = this.storeChange.bind(this);
store.subscribe(this.storeChange) //订阅Redux的状态
}
render() {
return (
<div>
<Input
placeholder={this.state.inputValue}
style={{width:'250px'}}
onChange={this.inputChangeValue.bind(this)}
/>
<Button type="primary" onClick={this.btnClick.bind(this)}>添加游戏</Button>
<List
bordered
dataSource={this.state.List}
renderItem={(item,index) => (
<List.Item onClick={this.deleteItem.bind(this,index)}>{item}</List.Item>
)}
/>
</div>
)
}
inputChangeValue(e){
const action = changeInputAction(e.target.value)
store.dispatch(action)
}
storeChange(){
this.setState(store.getState)
}
btnClick(){
const action=addItemAction();
store.dispatch(action)
}
deleteItem(index){
const action=deleteItemAction(index)
store.dispatch(action)
}
}
export default ToDoList;