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

原文地址:https://www.cnblogs.com/huangjie2018/p/10758580.html

时间: 2024-08-30 17:41:37

react--redux状态管理的相关文章

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

这个demo只有一个reducer 所以合并reducer这个demo用不到 ,但是我写出来这样大家以后可以用到,很好用,管理多个reducer,因为只要用到redux就不会只有一个reducer所以这个合并reducer很好用. 需要的技术:react-redux    redux实现状态管理 装饰器:transform-decorators-legacy下载 第一步下载transform-decorators-legacy npm install transform-decorators-l

Redux状态管理方法与实例

状态管理是目前构建单页应用中不可或缺的一环,也是值得花时间学习的知识点.React官方推荐我们使用Redux来管理我们的React应用,同时也提供了Redux的文档来供我们学习,中文版地址为http://cn.redux.js.org/index.html 前言 虽然官方文档上说只需几分钟就能上手 Redux,但是我个人认为即便你看个两三天也可能上手不了,因为文档里面的知识点不仅数量较多,而且还艰涩难懂,不结合一些实例来看很难用于实际项目中去. 但是不要担心自己学不会,这不我就给大家带来了这篇干

40行程序把Vue3的响应式集成进React做状态管理

本文参考原文-http://bjbsair.com/2020-03-22/tech-info/2095/ 前言 vue-next是Vue3的源码仓库,Vue3采用lerna做package的划分,而响应式能力@vue/reactivity被划分到了单独的一个package中. 如果我们想把它集成到React中,可行吗?来试一试吧. 使用示例 话不多说,先看看怎么用的解解馋吧. // store.ts import { reactive, computed, effect } from '@vue

nextjs的开发使用(二)---引入redux状态管理

在上篇文章中,基于react的nextjs服务端渲染框架学习使用 学习了解了一些关于nextjs的东西,并做了一个小demo,这篇文章将对上篇文章做一个补充,在nextjs中引入redux 安装 // 安装redux相关依赖 yarn add redux redux-saga react-redux // 安装next.js对于redux的封装依赖包 yarn add next-redux-wrapper next-redux-saga yarn add redux react-redux 创建

redux状态管理和react的结合使用

1:Redux Redux 是 JavaScript 状态容器,专注于状态管理的库 整体来说是单一状态.就是指的是单向的数据流 应用中所有的 state 都储存在 store 中. 惟一改变 state 的办法是dispatch触发 action,为了描述 action 如何改变 state ,需要编写 reducer. redux中最重要的几个:store     state     action    reducer 首先安装redux   安装:http://www.cnblogs.com

Mobx | 强大的状态管理工具 | 可以用Mobx来替代掉redux

来源简书 电梯直达 https://www.jianshu.com/p/505d9d9fe36a Mobx是一个功能强大,上手非常容易的状态管理工具.就连redux的作者也曾经向大家推荐过它,在不少情况下你的确可以使用Mobx来替代掉redux. 本教程旨在介绍其用法及概念,并重点介绍其与React的搭配使用. 先来看看最基本的用法. observable和autorun import { observable, autorun } from 'mobx'; const value = obse

react框架的状态管理

安装: cnpm install --save redux cnpm install --save react-redux 安装好后导入模块内容: impor {createStore} from 'redux' import {Provider,connect} from 'react-redux' 导入模块: import { createStore } from 'redux' //createStore方法用于创建管理状态的仓库对象 import { Provider,connect }

React项目中使用Mobx状态管理(二)

并上一节使用的是普通的数据状态管理,不过官方推荐使用装饰器模式,而在默认的react项目中是不支持装饰器的,需要手动启用. 官方参考 一.添加配置 官方提供了四种方法, 方法一.使用TypeScript,顾名思义该方法是项目使用typescript时的配置 方法二.使用babel-preset-mobx, 安装并添加到.babelrc配置中,该方法需要升级一些依赖, babel-core -> @/babel-core 7.x babel-loader -> @/babel-loader 8.

状态管理器 redux

简单修改state:let state = { count: 1 } 我们来使用下状态 console.log(state.count); 我们来修改下状态 state.count = 2; console.log(state.count); 实现了状态(计数)的修改和使用了. 上面的有一个很明显的问题:修改 count 之后,使用 count 的地方不能收到通知.我们可以使用发布-订阅模式来解决这个问题. /*------count 的发布订阅者实践------*/第一个版本: let sta

React + Redux + express+ antd 架构的认识

在过去的两周里,我使用这套技术栈进行项目页面的开发.下面是我个人的对于项目的一些看法: 首先:是项目的调试,我深表压力很大,项目是使用fibber去抓包调试的,也不知道我们项目的负责人,怎么能的我在每次更改代码,webpack重新打包压缩的时候总是很慢,当然也有可以是领导的电脑配置高.但是对于我这种刚来的菜鸟来说这样自测真的很慢啊,也不知道后期会不会更改了.刚入门的菜鸟表示压力很大. 第二:对于redux,我不知道前人是什么逻辑去使用这个状态管理器的,总感觉他们写的代码很乱,我理解起来很有难度,