栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

spring-boot react redux增删改查

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring-boot react redux增删改查

  1. 检出代码

git clone https://gitee.com/qinaichen/react-crud.gitcd 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;
}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;
}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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/235542.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号