Tip: Use useContext and useReducer build small redux

For communication between two sub-components, we believe that the development is not uncommon, based on how we do not like redux insistence ... ... In fact, I've been with the team boss had continued to write globalBus really fragrant, I also have an article on the principle and talked about that thing, but the boss said you can not have it now, the new hooks combined with two api, more fragrant, so I simply practice a lot and found ... really fragrant.

First you need to set up a layer on top of two sub-components of your context chilFirst and ChildSecond are two components I created, we will send dipatch from the first component, the data show changes in the second component, often used in this scenario development .

First we have to establish context, we need to change an initial state and a state of the state manager, Hey, how so much like this ... ..

// Context.js
export const defaultState = {
    value: 0
}

export function reducer(state, action) {
    switch(action.type) {
        case 'ADD_NUM':
            return { ...state, value: state.value + 1 };
        case 'REDUCE_NUM':
            return { ...state, value: state.value - 1 };
        default: 
            throw new Error();
    }
}

Content.js, where we need to explicitly declare Context.Provider the data to the package assembly, here turn powerful useReducer played, according to the official requirements, you need to reducer (we previously defined) and default incoming https: / /reactjs.org/docs/hooks-reference.html#usereducer , (use small hooks where the state assembly, when we changed the upper state, its components will be re-wrapped obtain a new value)

// Content.js
import React, { useReducer, createContext } from 'react'
import { ChildFirst } from './ChildFirst'
import { ChildSecond } from './ChildSecond'
import { reducer, defaultState } from './reducer'

export const Context = createContext(null)

export function Content() {
    const [state, dispatch] = useReducer(reducer, defaultState)

    return (
        <Context.Provider value={{state, dispatch: dispatch}}>
            <ChildFirst/>
            <ChildSecond/>
        </Context.Provider>
    )
} 

Components First, in this component of our dispatch send events to try

// ChildFirst.js
import React, {useContext} from 'react'
import {Context} from './content'

export function ChildFirst() {
    const AppContext = useContext(Context)

    return (
        <div>
            <button onClick={ 
                 () => {
                AppContext.dispatch({
                    type: "ADD_NUM",
                    payload: {}
                  })
                }
            }>addNum</button>
            <button onClick={
                () => {
                AppContext.dispatch({
                    type: "REDUCE_NUM",
                    payload: {}
                    })  
                }
            }>reduceNum</button>
        </div>
    )
} 

Second Component

// ChildSecond.js
import React, {useContext} from 'react'
import {Context} from './content'

export function ChildSecond() {
    const AppContext = useContext(Context)

    return (
        <div>
            {AppContext.state.value + 's'}
        </div>
    )
} 
6029918-0c8ecb5544900118.gif
DEMO

We have found the need to set up local assembly common context in some areas, not only conducive to decouple our organizational structure, we also avoid the cost of introducing the outset redux this global state library or introduced midway brings. As the state itself is not that an application needs of public administration, coupled with poor management team to develop the quality of different words, it is easy to abuse redux, greatly slow down the speed of the whole application, so learn this technique can be optimized between components lightweight performance and application state management.

Reproduced in: https: //www.jianshu.com/p/71efc5b579bd

Guess you like

Origin blog.csdn.net/weixin_34066347/article/details/91285391