日日行,不怕千万里

React- 使用 react 自身方法实现redux 功能

使用情况

  在我们工程中会遇到一些组件之间通信,多层嵌套,组件传值困难等问题,我们可以使用这样的方式进行传值:redux/mobx  等等插件实现组件数据共享。假如不存在这些我们本身使用react 如何实现现有的功能。

外层组件:建立 React.createContext();建立stroe;

import React, { useReducer, useState } from 'react';
import Child from './Child';
import { reducer, initialState } from './reducer';

export const { Provider, Consumer } = React.createContext({});
const UseReducer = () => {
    const [state, dispatch] = useReducer(reducer, initialState);
    return (
        <Provider value={{count: state.count, dispatch: dispatch}}>
            Count: {state.count}
            <Child />
            <button onClick={() => dispatch({type: 'decrement'})}>-</button>
            <button onClick={() => dispatch({type: 'increment'})}>+</button>
        </Provider>
    )
}

export default UseReducer;  

组件  reducer  数据处理部分:

const initialState = { 
    count: 0 
};

const reducer = (state, action) => {
    switch (action.type) {
        case 'increment':
            return { count: state.count + 1 };
        case 'decrement':
            return { count: state.count - 1 };
        default:
            throw new Error();
    }
}

export {
    reducer,
    initialState
}

组件使用部分:

import React, { useContext } from 'react';
import { Consumer } from './index';

const Child = () => {
    return (
        <Consumer>
            {(item) => {
                return (
                    <div onClick={() => item.dispatch({type: 'decrement'})}>这是父组件传递的值{item.count}</div>
                )
            }}
        </Consumer>
    )
}
export default Child; 

此时展示形势就是子组件中可以直接去触发父组件方法,同时多层嵌套数据也可调用到。初步实现数据共享,欢迎你的关注,麻烦点个赞。

 

posted @ 2020-09-23 10:51  GongXiaoZhu  阅读(160)  评论(0编辑  收藏  举报