环境准备
以spring-boot react一步一步实现增删改查 组件化为基础代码,在gis
分支的基础上,创建一个redux
分支,来集成redux
组件,实现增删改查
- 检出代码
git clone https://gitee.com/qinaichen/react-crud.git
cd 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;
}
/**
* 初始化list
*/
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;
}
/**
* 将state中的id和name设置为空
*/
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://gitee.com/qinaichen/react-crud.git 中的redux
分支