• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

React : Redux - 状态管理

武飞扬头像
玄鱼殇
帮助1

学新通

一、前言

1. 纯函数

函数式编程中有一个非常重要的概念叫纯函数,JavaScript符合函数式编程的范式,所以也有纯函数的概念
  • 确定的输入,一定会产生确定的输出

  • 函数在执行过程中,不能产生副作用

2. 副作用

表示在执行一个函数时,除了返回函数值之外,还对调用函数产生了附加的影响,
比如修改了全局变量,修改参数或者改变外部的存储
  • 纯函数在执行的过程中就是不能产生这样的副作用

  • 副作用往往是产生bug的 “温床”

3. 纯函数的案例

对数组操作的两个函数:
slice就是一个纯函数,不会修改数组本身,而splice函数不是一个纯函数
  • slice:slice截取数组时不会对原数组进行任何操作,而是生成一个新的数组

  • splice:splice截取数组, 会返回一个新的数组, 也会对原数组进行修改

学新通

4. 判断是否纯函数

学新通

5. 纯函数的作用和优势

纯函数在函数式编程中非常重要 :
  • 可以安心的编写和安心的使用

  • 在写的时候保证了函数的纯度,只是单纯实现业务逻辑即可,不需要关心传入的内容是如何获得的或者依赖其他的外部变量是否已经发生了修改

  • 在用的时候,确定的输入内容不会被任意篡改,并且确定的输入,一定会有确定的输出

6. 在React中

React中就要求无论是函数还是class声明一个组件,这个组件都必须像纯函数一样,保护它们的props不被修改
学新通

7. 为啥使用Redux

学新通

二、Redux的核心理念

1. 核心理念 - store

store : 用于存储共享数据的仓库

2. 核心理念 - action

action : store中所有数据的变化,必须通过派发(dispatch)action来更新
action是一个普通的JavaScript对象,用来描述这次更新的type和content

3. 核心理念 - reducer

reducer : reducer是一个纯函数,将state和action联系在一起
reducer做的事情就是将传入的state和action结合起来生成一个新的state

4. Redux的三大原则

单一数据源

  • 整个应用程序的state被存储在一颗object tree中,并且这个object tree只存储在一个 store

  • Redux并没有强制让我们不能创建多个Store,但是那样做并不利于数据的维护

  • 单一的数据源可以让整个应用程序的state变得方便维护、追踪、修改

State是只读的

  • 唯一修改State的方法一定是触发action,不要试图在其他地方通过任何的方式来修改State

  • 这样就确保了View或网络请求都不能直接修改state,它们只能通过action来描述自己想要如何修改state

  • 这样可以保证所有的修改都被集中化处理,并且按照严格的顺序来执行,所以不需要担心race condition(竟态)的问题

使用纯函数来执行修改

  • 通过reducer将 旧state和 actions联系在一起,并且返回一个新的State

  • 随着应用程序的复杂度增加,我们可以将reducer拆分成多个小的reducers,分别操作不同state tree的一部分

  • 但是所有的reducer都应该是纯函数,不能产生任何的副作用

三、Redux的基本使用

1. 测试项目搭建

01. 创建一个新的项目文件夹: learn-redux

02. 进入文件夹后进行项目初始化
npm init -y

03. 安装redux
npm install redux

04. 创建src目录,以及其中的index.js文件

05. 修改package.json可以执行index.js
也可不修改,直接控制台输入 node src/index.js
  1.  
     
  2.  
    "scripts": {
  3.  
    // node v13.2.0之后,添加属性:"type": "module",就可以在node中对ES6模块化的支持
  4.  
      "type": "module",
  5.  
    "start": "node src/index.js"
  6.  
    },

学新通

06. 在src中创建目录store,并创建index.js
  1.  
     
  2.  
    // 需要配置下type,否则的话直接使用commonjs也是可以的
  3.  
    import { createStore } from 'redux';
  4.  
     
  5.  
    // 1. 定义初始化数据
  6.  
    const initialState = {
  7.  
    name: 'coder',
  8.  
    age: 18,
  9.  
    counter: 100
  10.  
    };
  11.  
     
  12.  
    // 2. 定义reducer纯函数
  13.  
    // 2.1 reducer函数的第一个参数是state,第二个参数是action
  14.  
    // 2.2 reducer函数必须返回一个新的state,这个state会覆盖原来的state
  15.  
    // 2.3 reducer函数中,不能修改原来的state,必须返回一个新的state
  16.  
     
  17.  
    // 第一次调用reducer函数的时候,state是undefined,所以给state设置默认值,只会在第一次调用的时候生效
  18.  
    const reducer = (state = initialState, action) => {
  19.  
     
  20.  
    // 2.4 在这里,根据action的type,来决定如何修改state,返回一个新的state
  21.  
    switch (action.type) {
  22.  
        case 'xxx' : return {...state,...}
  23.  
      }
  24.  
      // 2.5 没有数据更新的时候,返回一个新的state
  25.  
    return state;
  26.  
    };
  27.  
     
  28.  
    // 3. 创建store
  29.  
    export const store = createStore(reducer);
学新通

2. 使用store中的数据

  1.  
     
  2.  
    // 1. 导入store
  3.  
    import { store } from './store/index.js';
  4.  
     
  5.  
    // 2. 拿到store中存储的数据
  6.  
    console.log(store.getState()); // { name: 'coder', age: 18, counter: 100 }

3. 修改store中的数据

执行代码
  1.  
     
  2.  
    // 导入store
  3.  
    import { store } from './store/index.js';
  4.  
     
  5.  
    // 创建一个action对象
  6.  
    const nameAction = { type: 'change_name', name: 'star' };
  7.  
    // 进行派发, 派发的时候,会调用reducer函数,传入state和action
  8.  
    store.dispatch(nameAction)
  9.  
     
  10.  
    // 创建一个action对象
  11.  
    const counterAction = { type: 'increment_counter', number: 10 };
  12.  
    // 进行派发
  13.  
    store.dispatch(counterAction);
  14.  
     
  15.  
    console.log(store.getState()); // { name: 'star', age: 18, counter: 110 }
学新通
在reducer函数中新增判断
  1.  
     
  2.  
    const reducer = (state = initialState, action) => {
  3.  
    // action => { type: 'change_name', name: 'star' }
  4.  
    switch (action.type) {
  5.  
    case 'change_name':
  6.  
    return {
  7.  
    // 先对原来staet进行解构
  8.  
    ...state,
  9.  
    // 再对name进行覆盖
  10.  
    name: action.name
  11.  
    };
  12.  
    case 'increment_counter':
  13.  
    return { ...state, counter: state.counter action.number };
  14.  
    default:
  15.  
    // 如果没有匹配到action.type,就返回原来的state
  16.  
    return state;
  17.  
    }
  18.  
    };
学新通

4. 订阅store中的数

  1.  
     
  2.  
    // 导入store
  3.  
    import { store } from './store/index.js';
  4.  
     
  5.  
    // 监听state的变化, 只要state发生了变化,就会调用回调函数
  6.  
    // 返回值是一个函数,调用这个函数,就可以取消监听
  7.  
    const unSubscribe = store.subscribe(() => {
  8.  
    console.log('state发生了变化');
  9.  
    console.log(store.getState());
  10.  
    });
  11.  
     
  12.  
    // 派发action => 可以监听到
  13.  
    store.dispatch({ type: 'change_name', name: 'star' });
  14.  
     
  15.  
    // 取消监听
  16.  
    unSubscribe();
  17.  
     
  18.  
    // 派发action => 不会监听到,但是state会发生变化,因为store.dispatch会调用reducer函数
  19.  
    store.dispatch({ type: 'increment_counter', number: 10 });
学新通

5. 优化

动态生成action

  1.  
     
  2.  
    // 导入store
  3.  
    import { store } from './store/index.js';
  4.  
     
  5.  
    store.subscribe(() => {
  6.  
    console.log('state发生了变化', store.getState());
  7.  
    });
  8.  
     
  9.  
    // 动态生成action : actionCreator => 创建action的函数, 返回一个action对象
  10.  
    const changeNameAction = (name) => ({ type: 'change_name', name });
  11.  
     
  12.  
    // store.dispatch({ type: 'change_name', name: 'star' });
  13.  
    // store.dispatch({ type: 'change_name', name: 'coderstar' });
  14.  
    store.dispatch(changeNameAction('star'));
  15.  
    store.dispatch(changeNameAction('coderstar'));
学新通

目录结构优化

如果将所有的逻辑代码写到一起,那么当redux变得复杂时代码就难以维护
对代码进行拆分,将store、reducer、action、constants拆分成一个个文件

创建store/index.js文件
  1.  
     
  2.  
    import { createStore } from 'redux';
  3.  
     
  4.  
    import reducer from './reducer.js';
  5.  
     
  6.  
    // 创建store
  7.  
    export const store = createStore(reducer);
创建store/reducer.js文件
  1.  
     
  2.  
    import { CHANGE_NAME, INCREMENT_COUNTER } from './constants.js';
  3.  
     
  4.  
    // 1. 定义初始化数据
  5.  
    const initialState = {
  6.  
    name: 'coder',
  7.  
    age: 18,
  8.  
    counter: 100
  9.  
    };
  10.  
     
  11.  
    // 2. 定义reducer
  12.  
    export const reducer = (state = initialState, action) => {
  13.  
    switch (action.type) {
  14.  
    case CHANGE_NAME:
  15.  
    return {
  16.  
    // 先对原来staet进行解构
  17.  
    ...state,
  18.  
    // 再对name进行覆盖
  19.  
    name: action.name
  20.  
    };
  21.  
    case INCREMENT_COUNTER:
  22.  
    return { ...state, counter: state.counter action.number };
  23.  
    default:
  24.  
    // 如果没有匹配到action.type,就返回原来的state
  25.  
    return state;
  26.  
    }
  27.  
    };
学新通
创建store/actionCreators.js文件 => 用于生成action
  1.  
     
  2.  
    // Description: Action Creators
  3.  
     
  4.  
    import { CHANGE_NAME, INCREMENT_COUNTER } from './constants.js';
  5.  
     
  6.  
    // 修改name名字的action
  7.  
    export const changeNameAction = (name) => ({ type: CHANGE_NAME, name });
  8.  
     
  9.  
    // 修改counter的action
  10.  
    export const incrementCounterAction = (number) => ({ type: INCREMENT_COUNTER, number });
创建store/constants.js文件 => 用于定义type常量
  1.  
     
  2.  
    // Desc: constants for actions
  3.  
     
  4.  
    export const CHANGE_NAME = 'change_name';
  5.  
    export const INCREMENT_COUNTER = 'increment_counter';

6. Redux使用流程图

学新通

学新通

四、React结合Redux

1. 安装

npm install redux

2. 基本使用

学新通

 store文件夹

index.js

  1.  
    import { createStore } from 'redux';
  2.  
    import { reducer } from './reducer';
  3.  
     
  4.  
    export const store = createStore(reducer);

 constants.js

  1.  
    export const CHANGE_COUNTER = 'change_counter';
  2.  
     
  3.  
    export const CHANGE_BANNER = 'change_banner';

reducer.js

  1.  
    import { CHANGE_BANNER, CHANGE_COUNTER } from './constants';
  2.  
     
  3.  
    const initialState = {
  4.  
    counter: 20,
  5.  
    bannerList: []
  6.  
    };
  7.  
     
  8.  
    export const reducer = (state = initialState, action) => {
  9.  
    switch (action.type) {
  10.  
    case CHANGE_COUNTER:
  11.  
    return { ...state, counter: state.counter action.counter };
  12.  
    case CHANGE_BANNER:
  13.  
    return { ...state, bannerList: [...state.bannerList, ...action.bannerList] };
  14.  
    default:
  15.  
    return state;
  16.  
    }
  17.  
    };
学新通

actionCreatores.js

  1.  
    import { CHANGE_COUNTER, CHANGE_BANNER } from './constants';
  2.  
     
  3.  
    // 修改counter的action
  4.  
    export const changeCounterAction = (counter) => ({ type: CHANGE_COUNTER, counter });
  5.  
     
  6.  
    // 修改bannerList的action
  7.  
    export const changeBannerAction = (bannerList) => ({ type: CHANGE_BANNER, bannerList });

page文件夹

Home.jsx

  1.  
    import React, { PureComponent } from 'react';
  2.  
    import { store } from '../store';
  3.  
    import { changeCounterAction } from '../store/actionCreatores.js';
  4.  
     
  5.  
    export class Home extends PureComponent {
  6.  
    constructor(porps) {
  7.  
    super(porps);
  8.  
     
  9.  
    this.state = {
  10.  
    // 从store中获取counter的值,赋予初始化值
  11.  
    counter: store.getState().counter
  12.  
    };
  13.  
    }
  14.  
    componentDidMount() {
  15.  
    // 监听store的变化
  16.  
    store.subscribe(() => {
  17.  
    this.setState({
  18.  
    counter: store.getState().counter
  19.  
    });
  20.  
    });
  21.  
    }
  22.  
    changeCounter(num) {
  23.  
    // 改变store中的值,通过dispatch派发action
  24.  
    store.dispatch(changeCounterAction(num));
  25.  
    }
  26.  
    render() {
  27.  
    const { counter } = this.state;
  28.  
    return (
  29.  
    <>
  30.  
    <h2>Home counter : {counter}</h2>
  31.  
    <button onClick={(e) => this.changeCounter(5)}> 5</button>
  32.  
    {' '}
  33.  
    <button onClick={(e) => this.changeCounter(10)}> 10</button>
  34.  
    </>
  35.  
    );
  36.  
    }
  37.  
    }
  38.  
     
  39.  
    export default Home;
学新通

Profily.jsx

  1.  
    import React, { PureComponent } from 'react';
  2.  
    import { store } from '../store';
  3.  
    import { changeCounterAction } from '../store/actionCreatores.js';
  4.  
     
  5.  
    export class Profily extends PureComponent {
  6.  
    constructor(porps) {
  7.  
    super(porps);
  8.  
     
  9.  
    this.state = {
  10.  
    // 从store中获取counter的值,赋予初始化值
  11.  
    counter: store.getState().counter
  12.  
    };
  13.  
    }
  14.  
    componentDidMount() {
  15.  
    // 监听store的变化
  16.  
    store.subscribe(() => {
  17.  
    this.setState({
  18.  
    counter: store.getState().counter
  19.  
    });
  20.  
    });
  21.  
    }
  22.  
    changeCounter(num) {
  23.  
    // 改变store中的值,通过dispatch派发action
  24.  
    store.dispatch(changeCounterAction(num));
  25.  
    }
  26.  
    render() {
  27.  
    const { counter } = this.state;
  28.  
    return (
  29.  
    <>
  30.  
    <h2>Profily counter : {counter}</h2>
  31.  
    <button onClick={(e) => this.changeCounter(-5)}>-5</button>
  32.  
    {' '}
  33.  
    <button onClick={(e) => this.changeCounter(-10)}>-10</button>
  34.  
    </>
  35.  
    );
  36.  
    }
  37.  
    }
  38.  
     
  39.  
    export default Profily;
学新通

App.jsx

  1.  
    import React, { PureComponent } from 'react';
  2.  
    import Home from './page/Home';
  3.  
    import Profily from './page/Profily';
  4.  
     
  5.  
    import { store } from './store';
  6.  
     
  7.  
    export class App extends PureComponent {
  8.  
    constructor(porps) {
  9.  
    super(porps);
  10.  
     
  11.  
    this.state = {
  12.  
    // 从store中获取counter的值,赋予初始化值
  13.  
    counter: store.getState().counter
  14.  
    };
  15.  
    }
  16.  
    componentDidMount() {
  17.  
    // 监听store的变化
  18.  
    store.subscribe(() => {
  19.  
    this.setState({
  20.  
    counter: store.getState().counter
  21.  
    });
  22.  
    });
  23.  
    }
  24.  
    render() {
  25.  
    const { counter } = this.state;
  26.  
    return (
  27.  
    <div style={{ textAlign: 'center', marginTop: '100px' }}>
  28.  
    <h2>App counter : {counter}</h2>
  29.  
    <hr />
  30.  
    <hr />
  31.  
    <hr />
  32.  
    <Home />
  33.  
    <hr />
  34.  
    <hr />
  35.  
    <hr />
  36.  
    <Profily />
  37.  
    </div>
  38.  
    );
  39.  
    }
  40.  
    }
  41.  
     
  42.  
    export default App;
学新通

3. react-redux的使用

  • redux和react没有直接的关系,完全可以在React, Angular, Ember, jQuery, or vanilla 
    JavaScript中使用Redux

  • redux依然是和React库结合的更好

  • redux官方帮助我们提供了 react-redux 的库,可以直接在项目中使用,并且实现的逻辑会更加的严谨和高效

将组件和store连接

安装 => npm install react-redux

1. 修改index.js 

  1.  
    import React from 'react';
  2.  
    import ReactDOM from 'react-dom/client';
  3.  
    import App from './App.jsx';
  4.  
    // 引入Provider组件, 用于给整个项目提供一个公共的store
  5.  
    import { Provider } from 'react-redux';
  6.  
    import { store } from './store';
  7.  
     
  8.  
    const root = ReactDOM.createRoot(document.querySelector('#root'));
  9.  
     
  10.  
    root.render(
  11.  
    <React.StrictMode>
  12.  
    {/* 给整个项目提供一个公共的store */}
  13.  
    <Provider store={store}>
  14.  
    <App />
  15.  
    </Provider>
  16.  
    </React.StrictMode>
  17.  
    );
学新通

2. 组件中使用

需要进行映射,state、dispatch都需要映射

  1.  
    import React, { PureComponent } from 'react';
  2.  
    // 1. 引入connect,用于连接组件和redux,返回一个高阶组件
  3.  
    import { connect } from 'react-redux';
  4.  
    import { changeCounterAction } from '../store/actionCreatores';
  5.  
     
  6.  
    export class About extends PureComponent {
  7.  
    changeCounter(num) {
  8.  
    // 4. 从props中取出changeCounter,不再从state中取,因为state中的值已经被映射到props中了
  9.  
    const { changeCounter } = this.props;
  10.  
    // 执行了下面定义的方法,相当于调用了dispatch(changeCounterAction(num))
  11.  
    changeCounter(num);
  12.  
    }
  13.  
    render() {
  14.  
    // 3. 从props中取出counter,不再从state中取,因为state中的值已经被映射到props中了
  15.  
    const { counter } = this.props;
  16.  
    return (
  17.  
    <>
  18.  
    <h2>About : {counter}</h2>
  19.  
    <button onClick={(e) => this.changeCounter(8)}> 8</button>
  20.  
    {' '}
  21.  
    <button onClick={(e) => this.changeCounter(-8)}>-8</button>
  22.  
    </>
  23.  
    );
  24.  
    }
  25.  
    }
  26.  
     
  27.  
    /**
  28.  
    * connect => connect()()返回一个高阶组件,第一个()传入两个参数,第二个()传入一个组件,返回一个新的 高阶组件🌟
  29.  
    * 第一个()传入两个参数,第一个参数是一个函数,第二个参数是一个对象
  30.  
    * 第一个参数函数,函数的参数是state,返回一个对象,对象的属性是state,值是state
  31.  
    * 第二个参数对象,对象的属性是一个函数,函数的参数是dispatch,返回一个对象,对象的属性是函数,函数的参数是参数,返回一个action
  32.  
    * 第二个()传入一个组件,返回一个新的组件
  33.  
    */
  34.  
    // 2. 注入store中的state和dispatch到组件的props中
  35.  
     
  36.  
    // 用来映射state中的值到组件的props中,可以设置取其中需要的数据
  37.  
    const mapStateToProps = (state) => ({ counter: state.counter });
  38.  
    // 用来映射dispatch到组件的props中,可以设置取其中需要的方法
  39.  
    const mapDispatchToProps = (dispatch) => ({
  40.  
    changeCounter: (num) => dispatch(changeCounterAction(num))
  41.  
    });
  42.  
     
  43.  
    export default connect(mapStateToProps, mapDispatchToProps)(About);
学新通

3. 组件中异步操作

学新通

About组件        =>   请求banners数据
Category组件   =>   展示banners数据

效果

学新通

About组件 
  1.  
    import React, { PureComponent } from 'react';
  2.  
    import { connect } from 'react-redux';
  3.  
    import { changeCounterAction, changeBannerAction } from '../store/actionCreatores';
  4.  
    import axios from 'axios';
  5.  
     
  6.  
    export class About extends PureComponent {
  7.  
    changeCounter(num) {
  8.  
    const { changeCounter } = this.props;
  9.  
    changeCounter(num);
  10.  
    }
  11.  
    async getData() {
  12.  
    const res = await axios.get('http://xxxxxx');
  13.  
    const bannerList = res?.data?.data?.banner?.list || [];
  14.  
    const { changeBanner } = this.props;
  15.  
    // 请求数据后,改变store中的值
  16.  
    changeBanner(bannerList);
  17.  
    }
  18.  
    render() {
  19.  
    const { counter } = this.props;
  20.  
    return (
  21.  
    <>
  22.  
    <h2>About : {counter}</h2>
  23.  
    <button onClick={(e) => this.changeCounter(8)}> 8</button>
  24.  
    {' '}
  25.  
    <button onClick={(e) => this.changeCounter(-8)}>-8</button>
  26.  
    {' '}
  27.  
    <button onClick={(e) => this.getData()}>请求数据</button>
  28.  
    </>
  29.  
    );
  30.  
    }
  31.  
    }
  32.  
     
  33.  
    const mapStateToProps = (state) => ({ counter: state.counter });
  34.  
    const mapDispatchToProps = (dispatch) => ({
  35.  
    changeCounter: (num) => dispatch(changeCounterAction(num)),
  36.  
    changeBanner: (bannerList) => dispatch(changeBannerAction(bannerList))
  37.  
    });
  38.  
     
  39.  
    export default connect(mapStateToProps, mapDispatchToProps)(About);
学新通
Category组件
  1.  
    import React, { PureComponent } from 'react';
  2.  
    import { connect } from 'react-redux';
  3.  
     
  4.  
    export class Category extends PureComponent {
  5.  
    render() {
  6.  
    const { bannerList } = this.props;
  7.  
    return (
  8.  
    <>
  9.  
    <h2>Category</h2>
  10.  
    <ul>
  11.  
    {bannerList.map((item, index) => {
  12.  
    return <li key={index}>{item.title}</li>;
  13.  
    })}
  14.  
    </ul>
  15.  
    </>
  16.  
    );
  17.  
    }
  18.  
    }
  19.  
     
  20.  
    const mapStateToProps = (state) => ({ bannerList: state.bannerList });
  21.  
     
  22.  
    export default connect(mapStateToProps, null)(Category);
学新通

4. redux中异步操作

上面的代码有一个缺陷

  • 必须将网络请求的异步代码放到组件的生命周期中来完成
  • 事实上,网络请求到的数据也属于状态管理的一部分,更好的一种方式应该是将其也交给redux来管理

学新通

redux中如何可以进行异步的操作 : 

  • 答案就是使用中间件(Middleware)
  • 学习过Express或Koa框架的童鞋对中间件的概念一定不陌生
  • 在这类框架中,Middleware可以帮助我们在请求和响应之间嵌入一些操作的代码,比如cookie解析、日志记录、文件压缩等操作

中间件

redux也引入了中间件(Middleware)的概念:

  • 这个中间件的目的是在dispatch的action和最终达到的reducer之间,扩展一些自己的代码
  • 比如日志记录、调用异步接口、添加代码调试功能等等
  • 发送异步的网络请求,可以使用中间件是 redux-thunk

redux-thunk是如何做到让我们可以发送异步的请求呢

  • 我们知道,默认情况下的dispatch(action),action需要是一个JavaScript的对象
  • redux-thunk可以让dispatch(action函数),action可以是一个函数
  • 该函数会被调用,并且会传给这个函数一个dispatch函数和getState函数
    • dispatch函数用于我们之后再次派发action
    • getState函数考虑到我们之后的一些操作需要依赖原来的状态,用于让我们可以获取之前的一些状态

redux-thunk的使用

安装    =>     npm install redux-thunk

store/index.js

  1.  
    // applyMiddleware => 应用中间件
  2.  
    import { createStore, applyMiddleware } from 'redux';
  3.  
     
  4.  
    import thunk from 'redux-thunk';
  5.  
    import { reducer } from './reducer';
  6.  
     
  7.  
    // 正常情况下,store.dispatch只能接收对象 store.dispatch(对象object)
  8.  
     
  9.  
    // 想要派发函数store.dispatch(函数function),需要对store进行增强,增强的方式是使用中间件
  10.  
    // 但是如果使用了redux-thunk中间件,那么store.dispatch就可以接收函数 store.dispatch(函数function)
  11.  
     
  12.  
    // 1. 引入中间件 applyMiddleware(thunk, logger, ...) => 可以传入多个中间件
  13.  
    const enhancer = applyMiddleware(thunk);
  14.  
    // 2. 使用中间件
  15.  
    export const store = createStore(reducer, enhancer);
学新通

actionCreatores.js

  1.  
    import axios from 'axios';
  2.  
    import { CHANGE_COUNTER, CHANGE_BANNER } from './constants';
  3.  
     
  4.  
    // 修改counter的action
  5.  
    export const changeCounterAction = (counter) => ({ type: CHANGE_COUNTER, counter });
  6.  
     
  7.  
    // 修改bannerList的action
  8.  
    export const changeBannerAction = (bannerList) => ({ type: CHANGE_BANNER, bannerList });
  9.  
     
  10.  
    // 异步获取bannerList的action
  11.  
    export const getBannerListAction = () => {
  12.  
    // 如果是普通的action,那么返回的是一个对象, {type: 'xxx', payload: 'xxx'}
  13.  
    // 问题:对象中不能直接拿到从服务器获取的数据
  14.  
    // return {}
  15.  
     
  16.  
    // 如果是函数,那么redux是不支持的,需要使用中间件redux-thunk
  17.  
    // 一旦派发来到这个函数,那么redux-thunk就会自动执行这个函数
  18.  
    // 这个函数的参数有来两个,第一个是dispatch => store.dispatch dispatch(xxx) , 第二个是getState => 获取store中的数据 getState().counter
  19.  
    return async (dispatch, getState) => {
  20.  
    const res = await axios.get('http://123.207.32.32:8000/home/multidata');
  21.  
    const bannerList = res?.data?.data?.banner?.list || [];
  22.  
    // 派发action对象
  23.  
    dispatch(changeBannerAction(bannerList));
  24.  
    };
  25.  
    };
学新通

About.jsx

  1.  
    import React, { PureComponent } from 'react';
  2.  
    import { connect } from 'react-redux';
  3.  
    import { changeCounterAction, getBannerListAction } from '../store/actionCreatores';
  4.  
     
  5.  
    export class About extends PureComponent {
  6.  
    changeCounter(num) {
  7.  
    const { changeCounter } = this.props;
  8.  
    changeCounter(num);
  9.  
    }
  10.  
    getData() {
  11.  
    const { getBannerList } = this.props;
  12.  
    // 在这里调用store中的action发送异步请求,获取数据
  13.  
    getBannerList();
  14.  
    }
  15.  
    render() {
  16.  
    const { counter } = this.props;
  17.  
    return (
  18.  
    <>
  19.  
    <h2>About : {counter}</h2>
  20.  
    <button onClick={(e) => this.changeCounter(8)}> 8</button>
  21.  
    {' '}
  22.  
    <button onClick={(e) => this.changeCounter(-8)}>-8</button>
  23.  
    {' '}
  24.  
    <button onClick={(e) => this.getData()}>请求数据</button>
  25.  
    </>
  26.  
    );
  27.  
    }
  28.  
    }
  29.  
     
  30.  
    const mapStateToProps = (state) => ({ counter: state.counter });
  31.  
    const mapDispatchToProps = (dispatch) => ({
  32.  
    changeCounter: (num) => dispatch(changeCounterAction(num)),
  33.  
    getBannerList: () => dispatch(getBannerListAction())
  34.  
    });
  35.  
     
  36.  
    export default connect(mapStateToProps, mapDispatchToProps)(About);
学新通

5. react调试工具 - redux-devtools

redux可以方便的让我们对状态进行跟踪和调试

  • redux官网为我们提供了redux-devtools的工具
  • 利用这个工具,我们可以知道每次状态是如何被修改的,修改前后的状态变化等等

步骤一 

在对应的浏览器中安装相关的插件

比如Chrome浏览器扩展商店中搜索Redux DevTools即可

学新通

学新通

步骤二

在redux中继承devtools的中间件

  1.  
    import { createStore, applyMiddleware, compose } from 'redux';
  2.  
     
  3.  
    import thunk from 'redux-thunk';
  4.  
    import { reducer } from './reducer';
  5.  
     
  6.  
    // redux-devtools-extension,用于在浏览器中查看redux的状态 => 为了安全,只在开发环境中使用
  7.  
    // 生产环境
  8.  
    let composeEnhancers = compose;
  9.  
    if (process.env.NODE_ENV === 'development') {
  10.  
    // 开发环境
  11.  
    composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ trace: true }) || compose;
  12.  
    }
  13.  
    const enhancer = applyMiddleware(thunk);
  14.  
     
  15.  
    export const store = createStore(reducer, composeEnhancers(enhancer));
学新通

学新通

6. Reducer文件拆分

学新通

拆分 

actionCreatores.js

  1.  
    import { CHANGE_COUNTER } from './constants';
  2.  
     
  3.  
    // 修改counter的action
  4.  
    export const changeCounterAction = (counter) => ({ type: CHANGE_COUNTER, counter });

constants.js

export const CHANGE_COUNTER = 'change_counter';

index.js

  1.  
    // 文件做统一的导出
  2.  
     
  3.  
    export { reducer as counterReducer } from './reducer';
  4.  
     
  5.  
    export * from './actionCreatores';

reducer.js

  1.  
    import { CHANGE_COUNTER } from './constants';
  2.  
     
  3.  
    const initialState = {
  4.  
    counter: 20
  5.  
    };
  6.  
     
  7.  
    export const reducer = (state = initialState, action) => {
  8.  
    switch (action.type) {
  9.  
    case CHANGE_COUNTER:
  10.  
    return { ...state, counter: state.counter action.counter };
  11.  
    default:
  12.  
    return state;
  13.  
    }
  14.  
    };

store   =>   下的index.js文件,用来合并各个模块的reducer

combineReducers函数可以方便的让我们对多个reducer进行合并

  1.  
    import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
  2.  
     
  3.  
    import thunk from 'redux-thunk';
  4.  
     
  5.  
    import { counterReducer } from './counter';
  6.  
    import { homeReducer } from './home';
  7.  
     
  8.  
    // 合并reducer
  9.  
    const reducer = combineReducers({
  10.  
    // 相当于模块名称
  11.  
    counter: counterReducer,
  12.  
    home: homeReducer
  13.  
    });
  14.  
     
  15.  
    // redux-devtools-extension,用于在浏览器中查看redux的状态 => 为了安全,只在开发环境中使用
  16.  
    // 生产环境
  17.  
    let composeEnhancers = compose;
  18.  
    if (process.env.NODE_ENV === 'development') {
  19.  
    // 开发环境
  20.  
    composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ trace: true }) || compose;
  21.  
    }
  22.  
    const enhancer = applyMiddleware(thunk);
  23.  
     
  24.  
    export const store = createStore(reducer, composeEnhancers(enhancer));
学新通

使用

直接取数据或者映射数据时,需要加上模块名

派发action还是和以前一样,不需要更改

学新通

五、ReduxToolkit

1. 概念

Redux Toolkit 是官方推荐的编写 Redux 逻辑的方法

  • 在前面我们学习Redux的时候应该已经发现,redux的编写逻辑过于的繁琐和麻烦
  • 并且代码通常分拆在多个文件中(虽然也可以放到一个文件管理,但是代码量过多,不利于管理)
  • Redux Toolkit包旨在成为编写Redux逻辑的标准方式,从而解决上面提到的问题
  • 在很多地方为了称呼方便,也将之称为“RTK”

安装      =>     npm install @reduxjs/toolkit react-redux

Redux Toolkit的核心API 

  • configureStore:包装createStore以提供简化的配置选项和良好的默认值
    • 它可以自动组合你的 slice reducer,添加你提供的任何 Redux 中间件,redux-thunk默认包含,并启用 Redux DevTools Extension
  • createSlice:接受reducer函数的对象、切片名称和初始状态值,并自动生成切片reducer,并带有相应的actions
  • createAsyncThunk: 接受一个动作类型字符串和一个返回承诺的函数,并生成一个pending/fulfilled/rejected基于该承诺分派动作类型的 thunk

2. 基本使用

store中的代码

counter.js   =>     store/peature/counter.js

  1.  
    // 1. 导入创建切片的函数
  2.  
    import { createSlice } from '@reduxjs/toolkit';
  3.  
     
  4.  
    const counterSlice = createSlice({
  5.  
    // 2. 切片名称
  6.  
    name: 'counter',
  7.  
    // 3. 初始状态
  8.  
    initialState: {
  9.  
    counter: 88
  10.  
    },
  11.  
    // 4. reducers => 相当于之前的reducer
  12.  
    reducers: {
  13.  
    // 5. 相当于之前的case,action.type就是这里的方法名称
  14.  
    changeCounterAction(state, action) {
  15.  
    state.counter = action.payload;
  16.  
    }
  17.  
    }
  18.  
    });
  19.  
     
  20.  
    // 6. 导出actions
  21.  
    export const { changeCounterAction } = counterSlice.actions;
  22.  
     
  23.  
    // 7. 导出reducer
  24.  
    export default counterSlice.reducer;
学新通

index.js   =>     store/index.js

  1.  
    import { configureStore } from '@reduxjs/toolkit';
  2.  
    import counterReducer from './features/counter';
  3.  
    import categoryReducer from './features/category';
  4.  
     
  5.  
    import thunk from 'redux-thunk';
  6.  
     
  7.  
    const store = configureStore({
  8.  
    // 1. reducer : 将切片的reducer添加到store中
  9.  
    reducer: {
  10.  
    counter: counterReducer,
  11.  
    category: categoryReducer
  12.  
    },
  13.  
    // 2. devTools : 开启redux-devtools,默认开启,开发环境开启,生产环境关闭
  14.  
    devTools: process.env.NODE_ENV === 'development',
  15.  
    // 3. middleware : 中间件,默认只有thunk,如果需要添加其他中间件,可以在这里添加
  16.  
    middleware: (getDefaultMiddleware) => {
  17.  
    return getDefaultMiddleware().concat(thunk);
  18.  
    },
  19.  
     
  20.  
    // 不常用的配置项
  21.  
    // 4. enhancers : 增强器,如果需要添加其他增强器,可以在这里添加
  22.  
    enhancers: [],
  23.  
    // 5. preloadedState : 初始状态,如果需要添加初始状态,可以在这里添加
  24.  
    preloadedState: {},
  25.  
    // 6. reducerPathInfo : reducer路径信息,如果需要添加reducer路径信息,可以在这里添加
  26.  
    reducerPathInfo: {},
  27.  
    // 7. middlewareFactories : 中间件工厂,如果需要添加中间件工厂,可以在这里添加
  28.  
    middlewareFactories: {},
  29.  
    // 8. devToolsEnhancerOptions : devTools增强器选项,如果需要添加devTools增强器选项,可以在这里添加
  30.  
    devToolsEnhancerOptions: {},
  31.  
    // 9. immutableCheck : 是否开启不可变检查,默认开启
  32.  
    immutableCheck: true,
  33.  
    // 10. serializableCheck : 是否开启序列化检查,默认开启
  34.  
    serializableCheck: true,
  35.  
    // 11. middlewareOptions : 中间件选项,如果需要添加中间件选项,可以在这里添加
  36.  
    middlewareOptions: {},
  37.  
    // 12. thunk : thunk中间件选项,如果需要添加thunk中间件选项,可以在这里添加
  38.  
    thunk: {},
  39.  
    });
  40.  
     
  41.  
    export default store;
学新通

主体index.js中的代码

  1.  
    import React from 'react';
  2.  
    import ReactDOM from 'react-dom/client';
  3.  
    import App from './App.jsx';
  4.  
    import { Provider } from 'react-redux';
  5.  
    import store from './store';
  6.  
     
  7.  
    const root = ReactDOM.createRoot(document.querySelector('#root'));
  8.  
     
  9.  
    root.render(
  10.  
    <React.StrictMode>
  11.  
    {/* 给整个项目提供一个公共的store */}
  12.  
    <Provider store={store}>
  13.  
    <App />
  14.  
    </Provider>
  15.  
    </React.StrictMode>
  16.  
    );
学新通

page中的代码

About.jsx    =>     page/About.jsx

  1.  
    import React, { PureComponent } from 'react';
  2.  
    import { connect } from 'react-redux';
  3.  
    import { changeCounterAction } from '../store/features/counter';
  4.  
     
  5.  
    export class About extends PureComponent {
  6.  
    changeCounter(num) {
  7.  
    // 通过props获取action
  8.  
    const { changeCounterAction } = this.props;
  9.  
    // 调用action
  10.  
    changeCounterAction(num);
  11.  
    }
  12.  
    render() {
  13.  
    const { counter } = this.props;
  14.  
    return (
  15.  
    <>
  16.  
    <h2>About : {counter}</h2>
  17.  
    <button onClick={(e) => this.changeCounter(8)}> 8</button>
  18.  
    {' '}
  19.  
    <button onClick={(e) => this.changeCounter(-8)}>-8</button>
  20.  
    </>
  21.  
    );
  22.  
    }
  23.  
    }
  24.  
     
  25.  
    // 映射Redux全局的state到组件的props上 => counter
  26.  
    const mapStateToProps = (state) => ({ counter: state.counter.counter });
  27.  
    // 映射dispatch到props上
  28.  
    const mapDispatchToProps = (dispatch) => ({
  29.  
    changeCounterAction: (num) => dispatch(changeCounterAction(num)),
  30.  
    });
  31.  
     
  32.  
    export default connect(mapStateToProps, mapDispatchToProps)(About);
学新通

3. 异步操作

之前通过redux-thunk中间件让dispatch中可以进行异步操作。
Redux Toolkit默认已经继承了Thunk相关的功能:createAsyncThunk

teAsyncThunk创建出来的action被dispatch时,会存在三种状态:

  • pending:action被发出,但是还没有最终的结果
  • fulfilled:获取到最终的结果(有返回值的结果)
  • rejected:执行过程中有错误或者抛出了异常
  • 可以在createSlice的entraReducer中监听这些结果

category.js   =>     store/peature/category.js

  1.  
    import axios from 'axios';
  2.  
    import { createSlice } from '@reduxjs/toolkit';
  3.  
    // 1. 导入createAsyncThunk,用于创建异步action
  4.  
    import { createAsyncThunk } from '@reduxjs/toolkit';
  5.  
     
  6.  
    // 2. 创建异步action
  7.  
    export const getBannerListAction = createAsyncThunk(
  8.  
    'home/getBannerListAction',
  9.  
    async (extraInfo, store) => {
  10.  
    // extraInfo => 是调用异步action时传入的参数 => {name: 'coder'}
  11.  
    // store => store对象,可以获取到store中的数据和dispatch方法,但是不推荐使用
  12.  
     
  13.  
    const res = await axios.get('http://123.207.32.32:8000/home/multidata');
  14.  
     
  15.  
    // 不能直接返回res,不支持序列化会报错,需要返回res.data
  16.  
    return res.data;
  17.  
    }
  18.  
    );
  19.  
     
  20.  
    const categorySlick = createSlice({
  21.  
    name: 'category',
  22.  
    initialState: {
  23.  
    bannerList: []
  24.  
    },
  25.  
    reducers: {
  26.  
    changeBannerListAction(state, { payload }) {
  27.  
    state.bannerList = payload;
  28.  
    }
  29.  
    },
  30.  
    // 3. 添加异步action的处理逻辑
  31.  
    extraReducers: {
  32.  
    // 不需要监听的话,可以不写
  33.  
    [getBannerListAction.pending]: (state, { payload }) => {
  34.  
    console.log('pending');
  35.  
    },
  36.  
    // 4. 在这里拿到异步action的结果,然后修改state
  37.  
    [getBannerListAction.fulfilled]: (state, { payload }) => {
  38.  
    state.bannerList = payload.data.banner.list;
  39.  
    },
  40.  
    // 不需要监听的话,可以不写
  41.  
    [getBannerListAction.rejected]: (state, { payload }) => {
  42.  
    console.log('rejected');
  43.  
    }
  44.  
    }
  45.  
    });
  46.  
     
  47.  
    // 6. 导出actions
  48.  
    export const { changeBannerListAction } = categorySlick.actions;
  49.  
     
  50.  
    // 7. 导出reducer
  51.  
    export default categorySlick.reducer;
学新通

Category.jsx   =>     page/Category.jsx 

  1.  
    import React, { PureComponent } from 'react';
  2.  
    import { connect } from 'react-redux';
  3.  
     
  4.  
    import { getBannerListAction } from '../store/features/category';
  5.  
    export class Category extends PureComponent {
  6.  
    componentDidMount() {
  7.  
    // 2. 在redux中进行数据请求
  8.  
    this.props.getBannerListAction();
  9.  
    }
  10.  
    render() {
  11.  
    // 4. 获取redux中的数据
  12.  
    const { bannerList } = this.props;
  13.  
    return (
  14.  
    <>
  15.  
    <h2>Category</h2>
  16.  
    <ul>
  17.  
    {bannerList.map((item, index) => {
  18.  
    return <li key={index}>{item.title}</li>;
  19.  
    })}
  20.  
    </ul>
  21.  
    </>
  22.  
    );
  23.  
    }
  24.  
    }
  25.  
     
  26.  
    // 3. 映射redux中的数据
  27.  
    const mapStateToProps = (state) => ({ bannerList: state.category.bannerList });
  28.  
     
  29.  
    // 1. 映射redux中的方法
  30.  
    const mapDispatchToProps = (dispatch) => ({
  31.  
    // 这里可以传递参数过去
  32.  
    getBannerListAction: () => dispatch(getBannerListAction({ name: 'coder' }))
  33.  
    });
  34.  
    export default connect(mapStateToProps, mapDispatchToProps)(Category);
学新通

4. 异步操作的另一种写法

extraReducer还可以传入一个函数,函数接受一个builder参数

  1.  
    /**
  2.  
    * extraReducer还可以传入一个函数,函数接受一个builder参数
  3.  
    * builder对象中包含了pending、fulfilled、rejected三个属性,分别对应异步action的三种状态
  4.  
    * builder对象中的属性值都是函数,函数的第一个参数是state,第二个参数是action
  5.  
    * builder对象中的属性值函数的返回值会直接赋值给state
  6.  
    */
  7.  
    extraReducers: (builder) => {
  8.  
    builder
  9.  
    .addCase(getBannerListAction.pending, (state, { payload }) => {
  10.  
    console.log('pending');
  11.  
    })
  12.  
    .addCase(getBannerListAction.fulfilled, (state, { payload }) => {
  13.  
    state.bannerList = payload.data.banner.list;
  14.  
    })
  15.  
    .addCase(getBannerListAction.rejected, (state, { payload }) => {
  16.  
    console.log('rejected');
  17.  
    });
  18.  
    }
学新通

5. Redux Toolkit的数据不可变性

学新通

六、其他补充

1. 自定义实现connect

组件中引入该文件即可,用法一致

实现代码

connect.js   =>     hoc/Category.js

  1.  
    /**
  2.  
    * 自定义实现 connect 函数
  3.  
    * @param {*} mapStateToProps => 函数
  4.  
    * @param {*} mapDispatchToProps => 函数
  5.  
    * @returns => 返回值也是函数,是个高级组件,接收一个组件作为参数
  6.  
    */
  7.  
     
  8.  
    // 1. 导入stroe
  9.  
    import store from '../store';
  10.  
     
  11.  
    export default function connect(mapStateToProps, mapDispatchToProps) {
  12.  
    // 返回一个高级组件
  13.  
    return function (WrappedComponent) {
  14.  
    class NewComponent extends WrappedComponent {
  15.  
    constructor(props) {
  16.  
    super(props);
  17.  
    // 2. 给state赋初始值
  18.  
    this.state = mapStateToProps(store.getState());
  19.  
    }
  20.  
    componentDidMount() {
  21.  
    // 3. 订阅store的变化, 一旦store发生变化,就会执行回调函数
  22.  
    this.unSubscribe = store.subscribe(() => {
  23.  
    // 4. 更新state
  24.  
    this.setState(mapStateToProps(store.getState()));
  25.  
     
  26.  
    // 直接调用父类的forceUpdate方法,强制更新, 但是不推荐使用
  27.  
    // this.forceUpdate();
  28.  
    });
  29.  
    }
  30.  
    componentWillUnmount() {
  31.  
    // 5. 取消订阅
  32.  
    this.unSubscribe();
  33.  
    }
  34.  
     
  35.  
    render() {
  36.  
    // 6. 拿到stateObj
  37.  
    const stateObj = mapStateToProps(store.getState());
  38.  
    // 7. 拿到dispatchObj
  39.  
    const dispatchObj = mapDispatchToProps(store.dispatch);
  40.  
    // 8. 合并stateObj和dispatchObj,传递给WrappedComponent
  41.  
     
  42.  
    return <WrappedComponent {...this.props} {...stateObj} {...dispatchObj} />;
  43.  
    }
  44.  
    }
  45.  
    return NewComponent;
  46.  
    };
  47.  
    }
学新通

优化代码

上面的connect函数有一个很大的缺陷:依赖导入的store

正确的做法是我们提供一个Provider,Provider来自于我们创建的Context,让用户将store传入到value中即可

  主体index.js中的代码

  1.  
    import React from 'react';
  2.  
    import ReactDOM from 'react-dom/client';
  3.  
    import App from './App.jsx';
  4.  
    import { Provider } from 'react-redux';
  5.  
    import store from './store';
  6.  
    // 导入StoreContext
  7.  
    import { StoreContext } from './hoc';
  8.  
     
  9.  
    const root = ReactDOM.createRoot(document.querySelector('#root'));
  10.  
     
  11.  
    root.render(
  12.  
    <React.StrictMode>
  13.  
    <Provider store={store}>
  14.  
    {/* 3. 使用StoreContext.Provider包裹App组件 => 把store传进去 */}
  15.  
    <StoreContext.Provider value={store}>
  16.  
    <App />
  17.  
    </StoreContext.Provider>
  18.  
    </Provider>
  19.  
    </React.StrictMode>
  20.  
    );
学新通

connect.js   =>     hoc/connect.js

  1.  
    /**
  2.  
    * 自定义实现 connect 函数
  3.  
    * @param {*} mapStateToProps => 函数
  4.  
    * @param {*} mapDispatchToProps => 函数
  5.  
    * @returns => 返回值也是函数,是个高级组件,接收一个组件作为参数
  6.  
    */
  7.  
     
  8.  
    // 不直接引入store, 而是从storeContext中获取
  9.  
    // import store from '../store';
  10.  
     
  11.  
    // 1. 引入storeContext
  12.  
    import { StoreContext } from './index.js';
  13.  
     
  14.  
    // 3. 这里的context就是store => 因为在index.js中,使用storeContext.Provider包裹了App组件,把store传进去了
  15.  
     
  16.  
    export function connect(mapStateToProps, mapDispatchToProps) {
  17.  
    // 返回一个高级组件
  18.  
    return function (WrappedComponent) {
  19.  
    class NewComponent extends WrappedComponent {
  20.  
    // 这里有两个参数,props和context,context就是store
  21.  
    constructor(props, context) {
  22.  
    super(props);
  23.  
    this.state = mapStateToProps(context.getState());
  24.  
    }
  25.  
    componentDidMount() {
  26.  
    this.unSubscribe = this.context.subscribe(() => {
  27.  
    this.setState(mapStateToProps(this.context.getState()));
  28.  
    });
  29.  
    }
  30.  
    componentWillUnmount() {
  31.  
    this.unSubscribe();
  32.  
    }
  33.  
     
  34.  
    render() {
  35.  
    const stateObj = mapStateToProps(this.context.getState());
  36.  
    const dispatchObj = mapDispatchToProps(this.context.dispatch);
  37.  
     
  38.  
    return <WrappedComponent {...this.props} {...stateObj} {...dispatchObj} />;
  39.  
    }
  40.  
    }
  41.  
     
  42.  
    // 2. 使用storeContext.Consumer包裹NewComponent组件, 传入store
  43.  
    NewComponent.contextType = StoreContext;
  44.  
    return NewComponent;
  45.  
    };
  46.  
    }
学新通

storeContext.js   =>     hoc/storeContext.js

  1.  
    // 1. 引入createContext, 用于创建上下文
  2.  
    import { createContext } from 'react';
  3.  
     
  4.  
    // 2. 创建上下文
  5.  
    export const StoreContext = createContext();

index.js   =>     hoc/index.js

  1.  
    // 统一的导出
  2.  
     
  3.  
    export { connect } from './connect';
  4.  
     
  5.  
    export { StoreContext } from './storeContext';

2. 打印日志需求

在dispatch之前 : 打印一下本次的action对象

在dispatch完成之后 : 打印一下最新的store state

01 - 手动修改

学新通

缺陷非常明显:

  • 首先,每一次的dispatch操作,都需要在前面加上这样的逻辑代码
  • 其次,存在大量重复的代码,会非常麻烦和臃肿

02 - 修改dispatch

利用一个hack一点的技术:Monkey Patching,利用它可以修改原有的程序逻辑

  • 直接修改了dispatch的调用过程
  • 在调用dispatch的过程中,真正调用的函数其实是dispatchAndLog
  1.  
    // 导出之前,做一层拦截,派发action之前,做一些事情,比如 => 打印日志
  2.  
    function interceptStoreLog(store) {
  3.  
    // 1. 拿到原始的dispatch方法
  4.  
    const next = store.dispatch;
  5.  
    // 2. 重写dispatch方法 => 在组件中派发action的时候,其实就是调用的这个方法
  6.  
    store.dispatch = function dispatchAndLog(action) {
  7.  
    console.log('当前派发的action', action);
  8.  
    // 3. 调用原始的dispatch方法,派发action
  9.  
    next(action);
  10.  
    console.log('派发之后的结果', store.getState());
  11.  
    };
  12.  
    }
  13.  
    interceptStoreLog(store);
  14.  
     
  15.  
    export default store;
学新通

3. 自定义实现thunk中间件

  1.  
    // 自定义实现thunk中间件
  2.  
    function thunkMiddleware(store) {
  3.  
    // 1. 拿到原始的dispatch方法
  4.  
    const next = store.dispatch;
  5.  
    // 2. 重写dispatch方法 => 在组件中派发action的时候,其实就是调用的这个方法
  6.  
    store.dispatch = function dispatchAndThunk(action) {
  7.  
    // 3. 判断action是不是函数
  8.  
    if (typeof action === 'function') {
  9.  
    // 4. 如果是函数,就调用这个函数,并且传入dispatch和getState方法 => 使用新的dispatch方法,因为可能又派发了函数
  10.  
    action(store.dispatch, store.getState);
  11.  
    } else {
  12.  
    // 5. 如果是对象,就调用原始的dispatch方法
  13.  
    next(action);
  14.  
    }
  15.  
    };
  16.  
    }
  17.  
    thunkMiddleware(store);
学新通

4. 合并自定义的中间件

目录修改

log.js        =>        middleware/log.js

  1.  
    // 导出之前,做一层拦截,派发action之前,做一些事情,比如 => 打印日志
  2.  
    export default function logMiddleware(store) {
  3.  
    // 1. 拿到原始的dispatch方法
  4.  
    const next = store.dispatch;
  5.  
    // 2. 重写dispatch方法 => 在组件中派发action的时候,其实就是调用的这个方法
  6.  
    store.dispatch = function dispatchAndLog(action) {
  7.  
    console.log('当前派发的action', action);
  8.  
    // 3. 调用原始的dispatch方法,派发action
  9.  
    next(action);
  10.  
    console.log('派发之后的结果', store.getState());
  11.  
    };
  12.  
    }

thunk.js        =>        middleware/thunk.js

  1.  
    // 自定义实现thunk中间件
  2.  
    export default function thunkMiddleware(store) {
  3.  
    // 1. 拿到原始的dispatch方法
  4.  
    const next = store.dispatch;
  5.  
    // 2. 重写dispatch方法 => 在组件中派发action的时候,其实就是调用的这个方法
  6.  
    store.dispatch = function dispatchAndThunk(action) {
  7.  
    // 3. 判断action是不是函数
  8.  
    if (typeof action === 'function') {
  9.  
    // 4. 如果是函数,就调用这个函数,并且传入dispatch和getState方法 => 使用新的dispatch方法,因为可能又派发了函数
  10.  
    action(store.dispatch, store.getState);
  11.  
    } else {
  12.  
    // 5. 如果是对象,就调用原始的dispatch方法
  13.  
    next(action);
  14.  
    }
  15.  
    };
  16.  
    }
学新通

index.js        =>        middleware/thunk.js 

  1.  
    export { default as logMiddleware } from './log';
  2.  
    export { default as thunkMiddleware } from './thunk';

合并

封装一个函数来实现所有的中间件合并

学新通

七、React中的state如何管理

目前主要有三种状态管理方式:

  • 方式一:组件中自己的state管理
  • 方式二:Context数据的共享状态
  • 方式三:Redux管理应用状态

推荐使用 : 

  • UI相关的组件内部可以维护的状态,在组件内部自己来维护
  • 大部分需要共享的状态,都交给redux来管理和维护
  • 从服务器请求的数据(包括请求的操作),交给redux来维护
  • 根据不同的情况会进行适当的调整

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfgajj
系列文章
更多 icon
同类精品
更多 icon
继续加载