一文弄懂redux、react-redux如何使用

5,555 阅读8分钟

「这是我参与2022首次更文挑战的第6天,活动详情查看:2022首次更文挑战

本文主要记录redux、以及react-redux的基础用法 image.png

一、redux

1.1 简介

(1)概念

  • 是一个专门用来做状态管理的js库(不是react插件
  • 可以用在vuereactangular项目中,但基本与react配合使用
  • 作用:集中式管理react应用中的多个组件共享的状态

(2)什么情况下需要使用redux

  • 某个组件的状态,需要让其他组件可以随时拿到(共享
  • 一个组件需要改变另一个组件的状态(通信
  • 总体原则:能不用就不用,如果不用比较吃力才用

1.2 工作流程

redux工作流程图如下: image.png

三个核心概念:

(1)action

  • 动作的对象
  • 包含两个属性
    • type属性标识,值为字符串,唯一,必要属性
    • data数据属性,值任意类型,可选属性
    • 例子{type:'ADD_STUDENT', data: {name: 'tom', age: '18'}} (2)reducer
  • 用于初始化、加工状态
  • 加工时,根据旧的state和action,产生新的state的纯函数

(3)store

  • stateactionreducer联系在一起的对象
  • 加工时,根据旧的state和action,产生新的state的纯函数

1.3 store

目录结构

│  └─ store
│     ├─ actions // actions,文件夹内以模块区分
│     │  ├─ count.js
│     │  └─ person.js
│     ├─ constants.js // action type唯一标识常量
│     ├─ index.js // 入口文件
│     └─ reducers // reducers,文件夹内以模块区分
│        ├─ conut.js
│        ├─ index.js // reducers统一暴露文件,合并reducers
│        └─ persons.js

引入createStore,专门用于创建redux中最为核心的store对象,而redux-thunkapplyMiddleware用于支持异步action,后文会讲到什么是异步action

// src/store/index.js
import { createStore, applyMiddleware } from "redux";
// 用于支持异步action
import thunk from "redux-thunk";
import reducers from "./reducers";

export default createStore(reducers, applyMiddleware(thunk));

1.4 action

定义action对象中type类型常量值消除魔法字符串

// src/store/constants.js
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'

创建action,普通action返回对象异步action返回函数

// src/store/actions/count.js
import { INCREMENT, DECREMENT } from "../constants";

// 普通action的值为object `{type: INCREMENT, data }`
export const increment = data => ({ type: INCREMENT, data });
export const decrement = data => ({ type: DECREMENT, data });

// 异步action的值为函数
export const incrementAsync = (data, time) => {
  return (dispatch) => {
    setTimeout(() => {
      dispatch(increment(data));
    }, time);
  };
};

异步action

  • 延迟的动作不想交给组件本身,想交给action
  • 何时需要异步action:想要对状态进行操作,但是具体的数据考异步任务返回

异步action不是必须要写的,完全可以自己等待异步任务的结果再去分发同步action

创建的action不再返回一个对象,而是一个函数,等异步任务有结果后,一般再去分发一个同步的action去真正操作数据

1.5 reducer

  • reducer函数会接到两个参数,分别为:之前的状态(preState)动作对象(action)
  • action对象中获取typedata
  • 根据type决定如何加工数据
import {INCREMENT, DECREMENT} from '../constants'
// 初始化状态
const initState = 0;

export default function count(preState = initState, action) {
  const { type, data } = action;
  switch (type) {
    case INCREMENT:
      return preState + data;
    case DECREMENT:
      return preState - data;
    default:
      return preState;
  }
}

(1)初始化状态

reducer里面没有设置初始值时,console.log(preState, action),在控制台如下图可以看到输出的preState=undefinedtype=@@redux/INITq.p.v.o.d.w

type redux内部处理为随机值,每次输出的都不一样 image.png 通过const initState = 0; export default function count(preState = initState, action) {....default: return preState;}设置初始值

(2)reducer是一个纯函数

// src/store/reducers/persons.js
import { ADD_PERSON } from "../constants";

const initState = [{ id: "001", name: "jona", age: "23" }];

export default function persons(preState = initState, action) {
  const { type, data } = action;
  switch (type) {
    case ADD_PERSON:
      // return preState.unshift(data) // 此处不可以这样写,这样会导致preState被改写了,personReducer就不是纯函数了,redux识别不到状态改变,视图不会更新了
      return [data, ...preState];
    default:
      return preState;
  }
}

补充纯函数概念 image.png

(3)合并reducers

通过combineReducers合并,接收的参数是一个对象,对象的key值与getState()得到的对象的key一致

// src/store/reducers/index.js
import { combineReducers } from "redux";
import count from "./conut";
import persons from "./persons";

export default combineReducers({
  count,
  persons,
});

1.6 getState、dispatch

  • 组件通过getState()拿store的数据
  • 通过dispatch触发状态更新
import store from "../../store";

import { increment } from "../../store/action/count";

 // 加法
  clickIncrement = () => {
    const { value } = this.selectNumber;
    store.dispatch(increment(value * 1));
  };
 render() {
    return (
      <div>
        <h1>当前求和为: {store.getState()}</h1>
        ...
        <button onClick={this.clickIncrement}>+</button>
      </div>  
      )
 }

视图不更新问题

dispatch后,发现store的值已经变化了但是视图不更新,如下图 image.png redux内部不支持自动更新,需要通过subscribeAPI监听redux中状态变化,只有变化,就需要重新调用render

componentDidMount() {
    store.subscribe(() => {
      this.forceUpdate();
    });
}

二、react-redux

2.1. react-redux VS redux

为了方便使用,Redux 的作者封装了一个 React 专用的库 React-Redux 这两个仓库的区别如下:

  • redux需要监听store变化更新视图,利用store.subscribe(() => { this.forceUpdate(); });react-redux不需要监听
  • react-redux将组件分为UI组件、容器组件;关于redux的操作都在容器组件中,单一职责原则;并通过connect(mapStateToProps, mapDispatchToProps)()连接容器组件与UI组件;redux没有区分

2.2 react-redux基本特性

React-Redux 将所有组件分成两大类:UI组件(presentational component)和容器组件(container component)

(1)UI组件有以下几个特征:

  • 只负责UI的呈现,不带有任何业务逻辑
  • 没有状态(即不使用this.state这个变量)
  • 所有数据都由参数(this.props)提供
  • 不使用任何 ReduxAPI (2)容器组件的特征恰恰相反
  • 负责管理数据和业务逻辑,不负责UI的呈现
  • 带有内部状态
  • 使用 ReduxAPI (3)UI组件容器组件关联
  • 所有的UI组件都应该包裹一个容器组件,它们是父子关系
  • 容器组件是真正与redux打交道的,里面可以随意调用redux的API
  • UI组件中不能使用任何redux API
  • 容器组件通过props给UI组件传递(1)redux中所保存的状态(2)用于操作状态的方法

总结:UI组件负责UI的呈现,容器组件负责管理数据和逻辑,如果一个组件既有UI又有业务逻辑,将它拆分成下面的结构:外面是一个容器组件,里面包了一个UI 组件。前者负责与外部的通信,将数据传给后者,由后者渲染出视图

2.3、connect()、mapStateToProps

React-Redux提供connect方法,用于从UI组件生成容器组件

下面代码中,CountUIUI组件,利用connect最后导出的是容器组件

为了定义业务逻辑,需要给出下面两方面的信息:

  • 输入逻辑:外部的数据(即state对象)如何转换为 UI 组件的参数
  • 输出逻辑:用户发出的动作如何变为 Action 对象,从 UI 组件传出去

connect方法接受两个参数:mapStateToPropsmapDispatchToProps。它们定义了 UI 组件的业务逻辑。前者负责输入逻辑,即将state映射到 UI 组件的参数(props),后者负责输出逻辑,即将用户对 UI 组件的操作映射成 Action

mapStateToProps 接收 state 参数,mapDispatchToProps 接收 dispatch 参数

// 容器组件
import { connect } from "react-redux";
import CountUI from "../../components/count";
import {
  createIncrementAction,
  createDecrementAction,
  createIncrementAsyncAction,
} from "../../redux/count_action";

const mapStateToProps = (state) => ({ count: state });

const mapDispatchToProps = (dispatch) => ({
  increment: (number) => {
    dispatch(createIncrementAction(number));
  },
  incrementAsync: (number) => {
    dispatch(createIncrementAsyncAction(number, 500));
  },
  decrement: (number) => {
    dispatch(createDecrementAction(number));
  },
});

export default connect(mapStateToProps, mapDispatchToProps)(CountUI);
// UI组件
import React, { Component } from "react";

export default class CountUI extends Component {
  // 加法
  increment = () => {
    const { value } = this.selectNumber;
    this.props.increment(value * 1);
  };

  // 减法
  decrement = () => {
    const { value } = this.selectNumber;
    this.props.decrement(value * 1);
  };

  // 奇数加
  incrementIfOdd = () => {
    if (this.props.count % 2 === 1) {
      const { value } = this.selectNumber;
      this.props.increment(value * 1);
    }
  };

  // 异步加
  incrementAsync = () => {
    const { value } = this.selectNumber;
    this.props.increment(value * 1);
  };

  render() {
    return (
      <div>
        <h1>当前求和为: {this.props.count}</h1>
        ...
      </div>
    );
  }
}

2.4、mapDispatchToProps

mapDispatchToPropsconnect函数的第二个参数,用来建立 UI 组件的参数到store.dispatch方法的映射。也就是说,它定义了哪些用户的操作应该当作 Action,传给 Store

它可以是一个函数,也可以是一个对象

(1)如果mapDispatchToProps是一个函数

// 容器组件
const mapDispatchToProps = (dispatch) => ({
  increment: (number) => {
    dispatch(createIncrementAction(number));
  },
  incrementAsync: (number) => {
    dispatch(createIncrementAsyncAction(number, 500));
  },
  decrement: (number) => {
    dispatch(createDecrementAction(number));
  },
});

// mapDispatchToProps的一般写法,返回function
export default connect(mapStateToProps, mapDispatchToProps)(CountUI);

(2)如果mapDispatchToProps是一个对象

键值是一个函数, Action creator ,返回的 Action 会由 Redux 自动发出

// mapDispatchToProps的简写,返回object
export default connect(mapStateToProps, {
  increment: createIncrementAction,
  incrementAsync: createIncrementAsyncAction,
  decrement: createDecrementAction,
})(CountUI);

2.5、Provider

connect方法生成容器组件以后,需要让容器组件拿到state对象,才能生成 UI 组件的参数。

一种解决方法是将state对象作为参数,传入容器组件。但是,这样做比较麻烦,尤其是容器组件可能在很深的层级,一级级将state传下去就很麻烦。

// src/App.js
import React, { Component } from "react";
import Count from "./container/count";
import store from "./redux/store";

export default class App extends Component {
  render() {
    return <Count store={store} />;
  }
}

React-Redux 提供Provider组件,可以让容器组件拿到state

Provider在根组件外面包了一层,这样一来,App的所有子组件就默认都可以拿到state

它的原理是React组件的context属性

使原来整个应用成为Provider的子组件 接收Reduxstore作为props,通过context对象传递给子孙组件上的connect

// src/index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import store from './redux/store'
import App from "./App";

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

写在最后

本文所有的例子在github,欢迎star,一起学习!