# 1.Type使用独立文件声明
//src/store/actionTypes.js
export const CHANGE_INPUT= 'changeInput';
export const ADD_ITEM= 'addItem';
export const REMOVE_ITEM= 'removeItem';
# 2.在ActionFactory中使用
//src/store/actionFactory.js
import {CHANGE_INPUT , ADD_ITEM , REMOVE_ITEM} from './actionTypes'
export const changeInputAction = (value)=> ({
type:CHANGE_INPUT,
value
});
export const addItemAction=()=>({
type:ADD_ITEM
});
export const removeItemAction=(index)=>({
type:REMOVE_ITEM,
index
});
# 3.使用ActionFactory派发Action
//引入
import {changeInputAction,addItemAction,removeItemAction} from './store/actionFactory'
//使用
changeInputValue(e){
const action = changeInputAction(e.target.value);
store.dispatch(action);
this.setState(store.getState())
}
# 4.完整代码
//src/TodoList.js
import React, {Component} from 'react';
import 'antd/dist/antd.css'
import {Input , Button ,List} from "antd";
import store from "./store";
import {changeInputAction,addItemAction,removeItemAction} from './store/actionFactory'
class TodoList extends Component {
constructor(props, context) {
super(props, context);
this.state = store.getState();
this.changeInputValue=this.changeInputValue.bind(this);
this.clickButton=this.clickButton.bind(this);
this.storeChange=this.storeChange.bind(this);
store.subscribe(this.storeChange)
}
render() {
return (
<div style={{margin:'10px'}}>
<div>
<Input
placeholder={this.state.inputValue}
value={this.state.inputValue}
style={{ width:'250px',marginRight:'10px',marginLeft:'10px'}}
onChange={this.changeInputValue}
/>
<Button
type="primary"
onClick={this.clickButton}
>提交</Button>
</div>
<div style={{ margin:'10px',width:'300px'}}>
<List
bordered
dataSource={this.state.list}
renderItem={(item,index) => (<List.Item onClick={this.removeList.bind(this,index)}>{item}</List.Item>)} />
</div>
</div>
);
}
changeInputValue(e){
const action = changeInputAction(e.target.value);
store.dispatch(action);
this.setState(store.getState())
}
storeChange(){
this.setState(store.getState())
}
clickButton(){
const action=addItemAction();
store.dispatch(action);
//this.setState(store.getState());
}
removeList(index){
const action=removeItemAction(index);
store.dispatch(action);
//this.setState(store.getState())
}
}
export default TodoList;
//src/store/actionFactory.js
import {CHANGE_INPUT , ADD_ITEM , REMOVE_ITEM} from './actionTypes'
export const changeInputAction = (value)=> ({
type:CHANGE_INPUT,
value
});
export const addItemAction=()=>({
type:ADD_ITEM
});
export const removeItemAction=(index)=>({
type:REMOVE_ITEM,
index
});