環境準備
以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
分支