1 store
2 reducer
3 component
4 action
过程
创建 (store + reducer)
import {createStore} form 'redux';
import reducer from './reducer.js';
const store = new createStore(reducer);
export default store;
创建 reducer.js
reducer内部只能读取state不能修改,需要使用深拷贝(json形式的数据对象)JSON.parse(JSON.stringfy(state))
const defaultState = {
name:'1'
}
export (state=defaultState,action)=>{
if (action.type == 'haha'){
let newState = JSON.parse(JSON.stringfy(state));
newState.name = action.value;
return newState;
}
return state;
}
component 内修改state
1.设置订阅 subscribe
- 创建action
3.dispatch(action) ==> 会自动传递给 reducer ==> store更新 ==>订阅更新component state
import store from './store';
class TodoList extend Component{
constructor(props){
super(props);
this.state = store.getState();
this.store.subscribe(this.updteState); //不订阅state不会更新
this.updteState = this.updteState.bind(this); //不要忘记这个
}
changeIpt(ev){
const action = {
type:'haha',
value:ev.target.value
}
}
updteState(){
this.setState(store.getState());
}
render(){
return (<input onChange={()=>{this.changeIpt()}}>)
}
}