♠ react-redux的使用


redux融入react代码

手动和redux联系

在 componentDidMount 中定义数据的变化,当数据发生变化时重新设置 counter;在发生点击事件时,调用store的dispatch来派发对应的action;

查看代码
//手动和redux联系
import React, { PureComponent } from 'react';

import store from '../store';
import {
  subAction
} from "../store/actionCreators";

export default class About extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      counter: store.getState().counter
    }
  }

  componentDidMount() {
    this.unsubscribue = store.subscribe(() => {
      this.setState({
        counter: store.getState().counter
      })
    })
  }

  componentWillUnmount() {
    this.unsubscribue();
  }

  render() {
    return (
      

About

当前计数: {this.state.counter}

) } decrement() { store.dispatch(subAction(1)); } subNumber(num) { store.dispatch(subAction(num)); } }

自定义connect函数

把手动订阅和取消订阅抽离到connect中

查看代码
import React, { PureComponent } from 'react';

import {connect} from '../utils/connect';
import {
  incAction,
  addAction
} from '../store/actionCreators'

class Home extends PureComponent {
  render() {
    return (
      

Home

当前计数: {this.props.counter}

) } } const mapStateToProps = state => ({ counter: state.counter }) const mapDispatchToProps = dispatch => ({ increment() { dispatch(incAction()); }, addNumber(num) { dispatch(addAction(num)); } }) export default connect(mapStateToProps, mapDispatchToProps)(Home);

但是上面的connect函数有一个很大的缺陷:依赖导入的store,如果我们将其封装成一个独立的库,需要依赖用于创建的store,我们应该如何去获取呢?难道让用户来修改我们的源码吗?不太现实;正确的做法是我们提供一个Provider,Provider来自于我们创建的Context,让用户将store传入到value中即可;

查看代码
import React, { PureComponent } from "react";

import { StoreContext } from './context';

export function connect(mapStateToProps, mapDispachToProp) {
  return function enhanceHOC(WrappedComponent) {
    class EnhanceComponent extends PureComponent {
      constructor(props, context) {
        super(props, context);

        this.state = {
          storeState: mapStateToProps(context.getState())
        }
      }

      componentDidMount() {
        this.unsubscribe = this.context.subscribe(() => {
          this.setState({
            storeState: mapStateToProps(this.context.getState())
          })
        })
      }

      componentWillUnmount() {
        this.unsubscribe();
      }

      render() {
        return 
      }
    }

    EnhanceComponent.contextType = StoreContext;

    return EnhanceComponent;
  }
}

react-redux使用

开始之前需要强调一下,redux和react没有直接的关系,你完全可以在React, Angular, Ember, jQuery, or vanilla JavaScript中使用Redux。虽然我们之前已经实现了connect、Provider这些帮助我们完成连接redux、react的辅助工具,但是实际上redux官方帮助我们提供了 react-redux 的库,可以直接在项目中使用,并且实现的逻辑会更加的严谨和高效。

安装react-redux:yarn add react-redux

react-redux源码导读

组件中异步操作

我们可以直接通过同步的操作来dispatch action,state就会被立即更新。但是真实开发中,redux中保存的很多数据可能来自服务器,我们需要进行异步的请求,再将数据保存到redux中。网络请求可以在class组件的componentDidMount中发送,所以我们可以有这样的结构:

上面的代码有一个缺陷:

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

1.安装redux-thunk,yarn add redux-thunk

2.在创建store时传入应用了middleware的enhance函数

  • 通过applyMiddleware来结合多个Middleware, 返回一个enhancer;
  • 将enhancer作为第二个参数传入到createStore中;

redux-devtools

redux可以方便的让我们对状态进行跟踪和调试,那么如何做到呢?

redux官网为我们提供了redux-devtools的工具;

利用这个工具,我们可以知道每次状态是如何被修改的,修改前后的状态变化等等;

安装该工具需要两步:

  • 第一步:在对应的浏览器中安装相关的插件(比如Chrome浏览器扩展商店中搜索Redux DevTools即可,其他方法可以参考GitHub);
  • 第二步:在redux中继承devtools的中间件;
查看代码
import { createStore, applyMiddleware, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createSagaMiddleware from 'redux-saga';

import saga from './saga';
import reducer from './reducer.js';

// composeEnhancers函数
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({trace: true}) || compose;

// 应用一些中间件
// 1.引入thunkMiddleware中间件(上面)
// 2.创建sagaMiddleware中间件
const sagaMiddleware = createSagaMiddleware();

const storeEnhancer = applyMiddleware(thunkMiddleware, sagaMiddleware);
const store = createStore(reducer, composeEnhancers(storeEnhancer));

sagaMiddleware.run(saga);

export default store;