hooks函数useReducer和useContext实现redux跨组件通信

目录

需求:父组件下两个子组件,点击1修改数据,在组件 2显示

reducer.js

父组件content.js

子组件1

子组件2


需求:父组件下两个子组件,点击1修改数据,在组件 2显示

思路: 

  1. 父组件通过createContext.Provider传递数据与方法
  2. 子组件通过useContext进行获取数据与方法
  3. 通过方法操作reducer

reducer.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

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 (
        
            
            
        
    )
}

子组件1

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

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

    return (
        
) }

子组件2

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

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

    return (
        
{AppContext.state.value + 's'}
) }

 

你可能感兴趣的:(前端)