Action和Reducer
书写action
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| handleChange(e){ const action = { type: 'change_input_value', value: e.target.value } store.dispatch(action) }
handleBtnClick(){ const action = { type:'add_todo_item' } store.dispatch(action) }
handleBtnDelete(index){ const action = { type:'delete_todo_item', index } store.dispatch(action) }
|
书写reducer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| const defaultState = { inputVlaue: '', list: [] }
export default (state = defaultState, action) => { if (action.type === 'change_input_value'){ const newState = JSON.parse(JSON.stringify(state)); newState.inputVlaue = action.value return newState; }
if (action.type === 'add_todo_item'){ const newState = JSON.parse(JSON.stringify(state)); newState.list.push(newState.inputVlaue) newState.inputVlaue = ''; return newState; }
if (action.type === 'delete_todo_item'){ const newState = JSON.parse(JSON.stringify(state)); newState.list.splice(action.index, 1); return newState; }
return state; }
|
订阅并修改值
1 2 3 4 5 6 7 8 9 10 11 12 13
| class TodoList extends Component{ constructor(props){ super(props); this.state = store.getState()
this.handleChange = this.handleChange.bind(this); this.handleStoreChange = this.handleStoreChange.bind(this) this.handleBtnClick = this.handleBtnClick.bind(this)
store.subscribe(this.handleStoreChange) }
|
1 2 3 4
| handleStoreChange(){ this.setState(store.getState()); }
|
https://github.com/rexyan/simple_react/tree/Action%E5%92%8CReducer