检出代码
git clone https://gitee.com/qinaichen/react-crud.gitcd react-crud
切换分支
git checkout gis
创建redux分支
git checkout -b redux添加redux库
cd web npm install redux --save创建store
src目录下创建store文件夹,并创建index.js
import { createStore } from 'redux'const store = createStore();export default store;store目录下创建reducer.js
const defaultState = {
id:'',
name:'', list:[]
}
export default (state = defaultState,action)=>{ return state;
}store中引入reducer
import { createStore } from 'redux'import reducer from './reducer'const store = createStore(reducer);export default store;store与组件结合使用将store引入App.js组件
import store from './store'
使用store中的数据对组件中的state进行初始化,并对store的数据进行订阅,当store中的数据发生变化时,组件中的数据也发生相应的变化
constructor(props) { super(props); this.state = store.getState();
store.subscribe(()=>{ this.setState(store.getState());
})
}修改App.js中的处理逻辑
edit = (item) => { const action = { type:'edit_user_name', user:item
}
store.dispatch(action)
}
query = () => {
axios.get('/user').then(({data})=>{ const action = { type:'init_user_list', list:data
};
store.dispatch(action);
})
}
handleChange = (name) =>{ const action = { type: 'change_user_name',
name
};
store.dispatch(action);
}
handleFormSubmit = (e) => {
e.preventDefault(); if(this.state.name !== ''){
axios.post('/user',{ id:!this.state.id?'':this.state.id, name:this.state.name
}).then(({data})=>{ const action = { type:'set_user_empty', user:{id:'',name:''}
}
store.dispatch(action); this.query();
})
}
}在reducer中添加相应的处理逻辑
if(action.type === 'change_user_name'){ const newState = Object.create(state);
newState.name = action.name; return newState;
}if(action.type === 'init_user_list'){ const newState = Object.create(state);
newState.list = action.list; return newState;
}if(action.type === 'edit_user_name'){ const newState = Object.create(state); const {id,name} = action.user;
newState.id = id;
newState.name = name; return newState;
}if(action.type === 'set_user_empty'){ const newState = Object.create(state); const {id,name} = action.user;
newState.id = id;
newState.name = name; return newState;
作者:心扬
链接:https://www.jianshu.com/p/929439b28842



