spring-boot react redux增刪改查

環境準備

spring-boot react一步一步實現增刪改查 組件化爲基礎代碼,在gis分支的基礎上,創建一個redux分支,來集成redux組件,實現增刪改查

  1. 檢出代碼
git clone https://gitee.com/qinaichen/react-crud.git

cd react-crud
  1. 切換分支
git checkout gis
  1. 創建redux分支
git checkout -b redux

添加redux

cd web

npm install redux --save

創建store

  1. src目錄下創建store文件夾,並創建index.js
import { createStore } from 'redux'

const store = createStore();

export default store;
  1. store目錄下創建reducer.js
const defaultState = {
    id:'',
    name:'',
    list:[]
}
export default (state = defaultState,action)=>{
	return state;
}
  1. store中引入reducer
import { createStore } from 'redux'
import reducer from './reducer'

const store = createStore(reducer);

export default store;

store與組件結合使用

  1. store引入App.js組件
import store from './store'
  1. 使用store中的數據對組件中的state進行初始化,並對store的數據進行訂閱,當store中的數據發生變化時,組件中的數據也發生相應的變化
constructor(props) {
	super(props);
	this.state = store.getState();
	store.subscribe(()=>{
		this.setState(store.getState());
	})
}
  1. 修改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();
        })
   }
}
  1. 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分支

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章