使用 React 新的 Context Api 来做状态管理

时间:2021-1-8 作者:admin

A react state management library using new context api.
中文介绍,点击这里

Installation

npm i mini-context-store --save

Basic Usage

  import React, { Fragment } from 'react'
  import createStore from 'mini-context-store'

  const { Provider, connect } = createStore(
    { counter: 0 },
    {
      onAdd: () => ({ counter }) => ({ counter: counter + 1 }),
      onSubtract: () => ({ counter }) => ({ counter: counter - 1 }),
    },
  )
  const identity = x => x
  let Counter = ({ counter, onAdd, onSubtract }) => (
    <Fragment>
      <span>{counter}</span>
      <button onClick={onAdd}>+1</button>
      <button onClick={onSubtract}>-1</button>
    </Fragment>
  )
  Counter = connect(identity, identity)(Counter)

  const App = () => <Provider><Counter /></Provider>

Examples

More examples click here

API

createStore

  const {Provider, Consumer, connect} = createStore(initialState, actions)

Provider

  <Provider>
    {/* children */}
  <Provider/>

A react component allows Consumers or connected component to subscribe the state changes.
NOTE: No need to pass value to Provider

Consumer

  <Consumer>
    {(state, actions) => /* use state and actions here */}
  </Consumer>

A react component subscribes state changes.

connect

  const EnchancedComponent = connect(mapStateToProps, mapStateToProps)(BaseComponent)

connect is a function receives two map functions and return a high-order component. The high-order component receives a BaseComponent, then return a EnchancedComponent that subscribes state changes. mapStateToProps and mapStateToProps are two pure functions. mapStateToProps receives state and return an object that will be merged in EnchancedComponent’ props. mapStateToProps receives actions and and return an object that will be merged in EnchancedComponent’ props.

Reference

声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。