React Hooks useContext + useReducer achieve simple Redux

context api is a simplified version of redux, he did not redux powerful ecosystem, combined with their middleware, for example thunk or saga, do data fetching or treatment side effect, but just want to keep some share data to avoid props drilling problems are more than enough.

  • context provides a method without the addition of each component manually props can transfer data between components of the tree
  • reducer should be pure functions, calculated according to the latest state of the old state and the new parameters, new parameters from a dispatch (new parameters) in

Using context redux still needs to look at, look at the cost, look after the scalability, maintainability.

React official website along with the document, first of all go to senior guidance -Context , focused on understanding React.createContext(initialValue)Provider and Consumer component method returns, it is the producer and consumer model.

Know the basic usage context, see the functional components useContext , focus to feel after using useContext, instead of before <MyContext.Consumer>such an approach, so Context of references easier.

Next, assume that you have already used itself Redux, Redux has a basic understanding of the processes that set, Redux itself is running out of React, this is a global database for state management, you can of course be used in conjunction with JQuery, but point of view, the reason why so popular, or because of a combination of React, so Redux in the React mainly dependent on the react-redux this library.

React to follow the official documentation for useReducer usage, which also provides useReducer about principles.

Believe me, although it may start elsewhere began to learn hooks, but definitely do not miss the official documentation.

We simulate redux similar functions, simple three-step process:

  1. Use useReducer in the root element and create the need to share the state to update its dispatch ()
  2. Use context api to just share of state and dispatch the same time continue
  3. Easy to use useContext underlying components shared read state
import React, { useContext, useReducer } from 'react';

const BankContext = React.createContext({});

// 和 redux 一样,综合根据旧 state 和 dispatch 而来的数据,计算出最新的 state
function reducer(state, action) {
  switch (action.type) {
    case 'deposit':
      return { balance: state.balance + action.payload };
    default:
      throw new Error();
  }
}

// 纯粹为了展示 useReducer 第三个参数
function init(initialCount) {
  return { balance: initialCount };
}

// 根组件
export default function App() {
  const [state, dispatch] = useReducer(reducer, 0, init);
  return (
    <BankContext.Provider value={{
      state,
      dispatch // 把 dispatch 也作为 context 的一部分共享下去,从而在嵌套组件中调用以实现更新顶层的 state
    }}>
      <Layout>
        <Content />
      </Layout>
    </BankContext.Provider>
  );
}

// 子组件
function Layout(props) {
  return (
    <div style={{ border: '5px solid lightblue', padding: '20px' }}>
      <p>您就当我是个 Layout 组件吧!</p>
      {props.children}
    </div>
  );
}

// 孙组件
// 经过层层嵌套后,可以在孙组件中读取全局 state 并设置
function Content() {
  // 这里不要误会,useContext(BankContext) 返回值就是我们共享出来的 context,
  // 只是这里刻意把 context 设计为对象,以便同时提供 dispatch
  const { state, dispatch } = useContext(BankContext);
  return (
    <div style={{ border: '1px solid #666' }}>
      <div> 当前余额:{state.balance}</div>
      <button onClick={() => dispatch({ type: 'deposit', payload: 100 })}>存入100元</button>
    </div>
  );
}

Guess you like

Origin www.cnblogs.com/nicholaswang/p/11887013.html
Recommended