明白 React 轻量状况治理库 Unstated

个人网站: https://www.neroht.com

在React写运用的时刻,不免碰到跨组件通讯的题目。如今已经有许多的解决方案。

  • React本身的Context
  • Redux连系React-redux
  • Mobx连系mobx-react

React 的新的Context api本质上并非React或许Mbox这类状况治理工具的替代品,充其量只是对React
本身状况治理短板的补充。而Redux和Mbox这两个库本身并非为React设想的,关于一些小型的React运用
比较重。

基础观点

Unstated是基于context API,也就是运用React.createContext()来竖立一个StateContext来通报状况的库

  • Container:状况治理类,内部运用state存储状况,经由历程setState完成状况的更新,api设想与React的组件基础一致。
  • Provider:返回Provider,用来包裹顶层组件,向运用中注入状况治理实例,可做数据的初始化。
  • Subscribe:本质上是Consumer,猎取状况治理实例,在Container实例更新状况的时刻强迫更新视图。

简朴的例子

我们拿最通用的计数器的例子来看unstated怎样运用,先邃晓一下构造:Parent作为父组件包括两个子组件:Child1和Child2。
Child1展现数字,Child2操纵数字的加减。然后,Parent组件的外层会包裹一个根组件。

保护状况

起首,同享状况须要有个状况治理的处所,与Redux的Reducer差别的是,Unstated是经由历程一个继续自Container实例:

import { Container } from 'unstated';

class CounterContainer extends Container {
  constructor(initCount) {
    super(...arguments);
    this.state = {count: initCount || 0};
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  }

  decrement = () => {
    this.setState({ count: this.state.count - 1 });
  }
}

export default CounterContainer

看上去是否是很熟悉?像一个React组件类。CounterContainer继续自Unstated暴露出来的Container类,应用state存储数据,setState保护状况,
而且setState与React的setState用法一致,可传入函数。返回的是一个promise。

同享状况

来看一下要显现数字的Child1组件,应用Subscribe与CounterContainer竖立联络。

import React from 'react'
import { Subscribe } from 'unstated'
import CounterContainer from './store/Counter'
class Child1 extends React.Component {
  render() {
    return <Subscribe to={[CounterContainer]}>
      {
        counter => {
          return <div>{counter.state.count}</div>
        }
      }
    </Subscribe>
  }
}
export default Child1

再来看一下要控制数字加减的Child2组件:

import React from 'react'
import { Button } from 'antd'
import { Subscribe } from 'unstated'
import CounterContainer from './store/Counter'
class Child2 extends React.Component {
  render() {
    return <Subscribe to={[CounterContainer]}>
      {
        counter => {
          return <div>
            <button onClick={counter.increment}>增添</button>
            <button onClick={counter.decrement}>削减</button>
          </div>
        }
      }
    </Subscribe>
  }
}
export default Child2

Subscribe内部返回的是StateContext.Consumer,经由历程to这个prop关联到CounterContainer实例,
运用renderProps形式衬着视图,Subscribe以内挪用的函数的参数就是定阅的谁人状况治理实例。
Child1Child2经由历程Subscribe定阅配合的状况治理实例CounterContainer,所以Child2能够挪用
CounterContainer以内的increment和decrement要领来更新状况,而Child1会依据更新来显现数据。

看一下父组件Parent

import React from 'react'
import { Provider } from 'unstated'
import Child1 from './Child1'
import Child2 from './Child2'
import CounterContainer from './store/Counter'

const counter = new CounterContainer(123)

class Parent extends React.Component {
  render() {
    return <Provider inject={[counter]}>
      父组件
      <Child1/>
      <Child2/>
    </Provider>
  }
}

export default Parent

Provider返回的是StateContext.Provider,Parent经由历程Provider向组件的高低文中注入状况治理实例。
这里,能够不注入实例。不注入的话,Subscribe内部就不能拿到注入的实例去初始化数据,也就是给状况一个默认值,比方上边我给的是123。

也能够注入多个实例:

<Provider inject={[count1, count2]}>
   {/*Components*}
</Provide>

那末,在Subscribe的时刻能够拿到多个实例。

<Subscribe to={[CounterContainer1, CounterContainer2]}>
  {count1, count2) => {}
</Subscribe>

剖析道理

弄邃晓道理之前须要先邃晓Unstated供应的三个API之间的关联。我依据本身的明白,画了一张图:

《明白 React 轻量状况治理库 Unstated》

来梳理一下全部流程:

  1. 竖立状况治理类继续自Container
  2. 天生高低文,new一个状况治理的实例,给出默认值,注入Provider
  3. Subscribe定阅状况治理类。内部经由历程_createInstances要领来初始化状况治理实例并定阅该实例,详细历程以下:
  • 从高低文中猎取状况治理实例,假如猎取到了,那它直接去初始化数据,假如没有猎取到

那末就用to中传入的状况治理类来初始化实例。

  • 将本身的更新视图的函数onUpdate经由历程定阅到状况治理实例,来完成实例内部setState的时刻,挪用onUpdate更新视图。
  • _createInstances要领返回竖立的状况治理实例,作为参数通报给renderProps挪用的函数,函数拿到实例,操纵或显现数据。

Container

用来完成一个状况治理类。能够明白为redux中action和reducer的连系。观点相似,但完成差别。来看一下Container的源码

export class Container {
  constructor() {
    CONTAINER_DEBUG_CALLBACKS.forEach(cb => cb(this));
    this.state = null;
    this.listeners = [];
  }

  setState(updater, callback) {
    return Promise.resolve().then(() => {
      let nextState = null;
      if (typeof updater === 'function') {
        nextState = updater(this.state);
      } else {
        nextState = updater;
      }

      if (nextState === null) {
        callback && callback();
      }
      // 返回一个新的state
      this.state = Object.assign({}, this.state, nextState);
      // 实行listener,也就是Subscribe的onUpdate函数,用来强迫革新视图
      const promises = this.listeners.map(listener => listener());

      return Promise.all(promises).then(() => {
        if (callback) {
          return callback();
        }
      });
    });
  }

  subscribe(fn) {
    this.listeners.push(fn);
  }

  unsubscribe(fn) {
    this.listeners = this.listeners.filter(f => f !== fn);
  }
}

Container包括了state、listeners,以及setState、subscribe、unsubscribe这三个要领。

  • state来寄存数据,listeners是一个数组,寄存更新视图的函数。
  • subscribe会将更新的函数(Subscribe组件内的onUpdate)放入linsteners。
  • setState和react的setState相似。实行时,会依据更改返回一个新的state,

同时轮回listeners挪用个中的更新函数。到达更新页面的结果。

  • unsubscribe用来作废定阅。

Provider

Provider本质上返回的是StateContext.Provider。

export function Provider(ProviderProps) {
  return (
    <StateContext.Consumer>
      {parentMap => {
        let childMap = new Map(parentMap);

        if (props.inject) {
          props.inject.forEach(instance => {
            childMap.set(instance.constructor, instance);
          });
        }

        return (
          <StateContext.Provider value={childMap}>
            {props.children}
          </StateContext.Provider>
        );
      }}
    </StateContext.Consumer>
  );
}

它本身吸收一个inject属性,经由处置惩罚后,将它作为context的值传入到高低文环境中。
能够看出,传入的值为一个map,运用Container类作为键,Container类的实例作为值。
Subscribe会吸收这个map,优先运用它来实例化Container类,初始化数据

能够有人注重到了Provider不是直接返回的StateContext.Provider,而是套了一层
StateContext.Consumer。如许做的目标是Provider以内还能够嵌套Provider。
内层Provider的value能够继续自外层。

Subscribe

简朴来讲就是衔接组件与状况治理类的一座桥梁,能够设想成react-redux中connect的作用

class Subscribe extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.instances = [];
    this.unmounted = false;
  }

  componentWillUnmount() {
    this.unmounted = true;
    this.unsubscribe();
  }

  unsubscribe() {
    this.instances.forEach((container) => {
      container.unsubscribe(this.onUpdate);
    });
  }

  onUpdate = () => new Promise((resolve) => {
    if (!this.unmounted) {
      this.setState(DUMMY_STATE, resolve);
    } else {
      resolve();
    }
  })

  _createInstances(map, containers) {
    this.unsubscribe();

    if (map === null) {
      throw new Error('You must wrap your <Subscribe> components with a <Provider>');
    }

    const safeMap = map;
    const instances = containers.map((ContainerItem) => {
      let instance;

      if (
        typeof ContainerItem === 'object' &&
        ContainerItem instanceof Container
      ) {
        instance = ContainerItem;
      } else {
        instance = safeMap.get(ContainerItem);

        if (!instance) {
          instance = new ContainerItem();
          safeMap.set(ContainerItem, instance);
        }
      }

      instance.unsubscribe(this.onUpdate);
      instance.subscribe(this.onUpdate);

      return instance;
    });

    this.instances = instances;
    return instances;
  }

  render() {
    return (
      <StateContext.Consumer>
        {
          map => this.props.children.apply(
            null,
            this._createInstances(map, this.props.to),
          )
        }
      </StateContext.Consumer>
    );
  }
}

这里比较主要的是_createInstances与onUpdate两个要领。StateContext.Consumer吸收Provider通报过来的map,
与props吸收的to一并传给_createInstances。

onUpdate:没有做什么其他事变,只是应用setState更新视图,返回一个promise。它存在的意义是在定阅的时刻,
作为参数传入Container类的subscribe,扩大Container类的listeners数组,随后在Container类setState转变状况今后,
轮回listeners的每一项就是这个onUpdate要领,它实行,就会更新视图。

_createInstances: map为provider中inject的状况治理实例数据。假如inject了,那末就用map来实例化数据,
否则用this.props.to的状况治理类来实例化。以后挪用instance.subscribe要领(也就是Container中的subscribe),
传入本身的onUpdate,完成定阅。它存在的意义是实例化Container类并将本身的onUpdate定阅到Container类实例,
终究返回这个Container类的实例,作为this.props.children的参数并举行挪用,所以在组件内部能够举行相似如许的操纵:

 <Subscribe to={[CounterContainer]}>
   {
     counter => {
       return <div>
         <Button onClick={counter.increment}>增添</Button>
         <Button onClick={counter.decrement}>削减</Button>
       </div>
     }
   }
</Subscribe>

总结

Unstated上手很轻易,明白源码也不难。重点在于明白宣布(Container类),Subscribe组件完成定阅的思绪。
其API的设想贴合React的设想理念。也就是想要转变UI必需setState。别的能够不必像Redux一样写许多榜样代码。

明白源码的历程当中受到了下面两篇文章的启示,衷心感谢:

地道极简的react状况治理组件unstated

Unstated浅析

    原文作者:nero
    原文地址: https://segmentfault.com/a/1190000018795861
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞