spring-boot react redux增刪改查
環境準備
以ofollow,noindex">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
分支