react--redux状态管理

Posted huangjie2018

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react--redux状态管理相关的知识,希望对你有一定的参考价值。

为了解决组件嵌套太深的问题状态管理的概念在前端横空出世,本文使用redux作为例子,先安装两个包
"react-redux": "^7.0.2", "redux": "^4.0.1", npm install redux react-redux --save

技术图片

新增pages/reduxComponent.js, 内容如下

import React, { Component } from ‘react‘;
import { connect } from ‘react-redux‘;
import { addCart, updateCart, deleteCart }  from ‘../redux/action/cartAction‘;


const mapStateToProps = (state) => {
    return {
        cart: state.CartReducers.cart
    }
};
const mapDispatchToProps = (dispatch) => {
    return {
        addCart: (...args) => dispatch(addCart(...args)),
        updateCart: (...args) => dispatch(updateCart(...args)),
        deleteCart: (...args) => dispatch(deleteCart(...args))
    }
};

class ReduxComponent extends Component {
    constructor(props){
        super(props);
        this.state = {
            count: 0,
        }
    }

    add = () => {
        const {count} = this.state;
        const newCount = count+1;
        this.props.addCart(‘a‘+ newCount, 2, 500, newCount);
        this.setState({
            count: newCount
        })
    };

    update = (id) => {
        const {count} = this.state;
        this.props.updateCart(‘b‘ + count, 3, 900, id)
    };

    delete = (id) => {
        this.props.deleteCart(id)
    };

    render() {
        return (
            <div style={{width:500, textAlign:‘center‘, margin: ‘30px auto‘}}>
                {
                    this.props.cart && this.props.cart.map((el, index) => {
                        return (
                            <div key={index}>
                                <p>
                                    {el.name} => {el.num} => {el.weight}
                                    <button onClick={this.update.bind(this, el.id)}>更新</button>
                                    <button onClick={this.delete.bind(this, el.id)}>删除</button>
                                </p>
                            </div>
                        )
                    })
                }
                <button onClick={this.add}>添加</button>
            </div>
        );
    }
}

export default connect(mapStateToProps,mapDispatchToProps)(ReduxComponent);

新增redux/active/cartActive.js, 内容如下

const ADD_CART = ‘ADD_CART‘;
const UPDATE_CART = ‘UPDATE_CART‘;
const DELETE_CART = ‘DELETE_CART‘;

export const addCart = (name, num, weight, id) => {
    return {
        type: ADD_CART,
        payload: {name, num, weight, id}
    }
};

export const updateCart = (name, num, weight, id) => {
    return {
        type: UPDATE_CART,
        payload: {name, num, weight, id}
    }
};

export const deleteCart = (id) => {
    return {
        type: DELETE_CART,
        payload: {id}
    }
};

新增redux/reducers/cardReducers.js, 内容如下

const initState ={
    cart: []
};

export default function(state=initState, action) {
    switch (action.type) {
        case ‘ADD_CART‘:
            return {
                ...state,
                cart: [...state.cart, action.payload]
            };
        case ‘UPDATE_CART‘:
            return {
                ...state,
                cart: state.cart.map(el => el.id === action.payload.id ? action.payload : el)
            };
        case ‘DELETE_CART‘:
            return {
                ...state,
                cart: state.cart.filter(el => el.id !== action.payload.id)
            };
        default:
            return state;
    }
}

新增redux/reducers/index.js, 内容如下

import {combineReducers} from ‘redux‘;
import CartReducers from ‘./cartReducers‘;

const allReducers = {
    CartReducers
};

const rootReducers = combineReducers(allReducers);

export default rootReducers

新增redux/store.js, 内容如下

import {createStore} from ‘redux‘;
import RootReducers from ‘./reducers‘;

const store = createStore(RootReducers);

export default store;

主入口index.js修改如下

import React from ‘react‘;
import ReactDOM from ‘react-dom‘;
import {HashRouter as Router} from ‘react-router-dom‘;
import { Provider } from ‘react-redux‘;
import store from ‘./redux/store.js‘;
import ‘./index.css‘;
// import App from ‘./App‘;
import routers from ‘./route‘;
import * as serviceWorker from ‘./serviceWorker‘;

ReactDOM.render(
    <Provider store={store}>
        <Router>{routers}</Router>
    </Provider>
    , document.getElementById(‘root‘));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

route/index.js修改如下
import React from ‘react‘;
import {Switch, Route} from "react-router-dom";
import asyncComponent from ‘../lazy‘;

import Home2 from ‘../pages/Home2‘;
import OnePage from ‘../pages/OnePage‘;
import TwoPage from ‘../pages/TwoPage‘;
import This from ‘../pages/This‘;
import Mount from ‘../pages/Mount‘;
import HooksTest1 from ‘../hooks/test1‘;
import AxiosTest from ‘../pages/AxiosTest‘;
import Refs from ‘../pages/Ref‘;
import ReduxComponent from ‘../pages/reduxComponent‘;
//import HooksUseState from ‘../hooks/useState‘;
const HooksUseState = asyncComponent(() => import (‘../hooks/useState‘));


const Routers = (
    <Switch>
        <Route path="/" exact component={Home2} />
        <Route path="/onePage" component={OnePage} />
        <Route path="/twoPage/:id" component={TwoPage} />
        <Route path="/this" component={This} />
        <Route path="/mount"  component={Mount} />
        <Route path="/hooksTest1" component={HooksTest1} />
        <Route path="/axiosTest" component={AxiosTest} />
        <Route path="/refs" component={Refs} />
        <Route path="/reduxComponent" component={ReduxComponent} />
        <Route path="/hooksUseState" component={HooksUseState} />
    </Switch>
);

export default Routers

启动项目,打开http://localhost:3000/#/reduxComponent   点击按钮试试,增删改都可以,主要看调用顺序和state操作,不懂的可以下项目代码自己启动看看,项目路径在https://github.com/huangjie2016/reacts

以上是关于react--redux状态管理的主要内容,如果未能解决你的问题,请参考以下文章

如何在 React/Redux 中本地管理组件的状态

react+redux状态管理实现排序 合并多个reducer文件

React Redux 状态将在使用 Nginx 更改路由时初始化

react redux 公共状态管理---数据的渲染,数据的修改,再把修改的数据渲染到当前组件

node.js 中的多人游戏架构 - 与 Redux 的状态管理和同步

如何在挂钩中比较来自 react redux 状态的值