spring-boot react redux增删改查
标签:
SpringBoot
检出代码
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;
}/**
* 初始化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://www.jianshu.com/p/929439b28842
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦