redux/index.js:
import { createStore } from 'redux';
// state
const todo_list_state = [
"eat",
"sleep"
]
// reducer
const todo_list_reducer = (state, action) => {
state = state || todo_list_state;
switch(action.type){
case "ADD_TODO":
return state.concat(action.payload);
case "DELETE_TODO":
return state.filter( (item, index) => index !== action.payload.index )
default:
return state;
}
}
// store
const store = createStore(todo_list_reducer);
export default store;
Components/CountTool.js:
import React, {Component} from 'react';
import store from '../redux/index';
class CountTool extends Component{
constructor(props){
super(props);
this.state = {
new_todo: "",
todo_list: store.getState()
}
}
set_new_todo = (e) => {
this.setState({
new_todo: e.target.value
})
}
add_new_todo = () => {
store.dispatch({
type: "ADD_TODO",
payload: this.state.new_todo
});
this.setState({
new_todo: ""
})
}
delete_todo = (index) => {
store.dispatch({
type: "DELETE_TODO",
payload: {
index: index
}
})
this.setState({
todo_list: store.getState()
})
}
render(){
return (
<>
<ul>
{this.state.todo_list.map( (item, index) => {
return (
<li key={index}>
待办: {item} <button onClick={() => this.delete_todo(index)}>×</button>
</li>
)
} )}
</ul>
<input value={this.state.new_todo} onChange={this.set_new_todo} />
<button onClick={this.add_new_todo}>添加</button>
</>
)
}
}
export default CountTool;
reducer => 实际处理状态的函数。第二个参数为action(行为),依次来进行状态state的操作,返回新的state;第一个参数在store(仓库)初始化时进行对state(状态)的初始化。
store.dispatch => 发送action(行为),参数为一个对象(action),action.type为reducer内部判断如何操作state的依据。
可以类比一下:store是一个工厂,state是工厂里面的资源,dispatch就是进出口部门(运货的),reducer就是保安、物管。