useContext的使用

  1. 首先我们需要创建一个context来挂载我们useReducer创建的redux
    //context.js 创建context
    import { createContext } from 'react';
    
    export default createContext(null);
  2. 在context上挂载我们useReducer创建出的redux,通过context提供的Provider组件
    //APP父组件 挂载redux
    import reducer from './store/reducer';
    import PersonalContext from '../../context';
    const [personalState, personalDispatch] = useReducer(reducer, { name: '123' });
    
    <PersonalContext.Provider value={{ personal: { personalState, personalDispatch } }}>
       <Home />
    </PersonalContext.Provider>
  3. 接下来我们就可以通过这个context来获取到挂载在上面的redux,使用方法有两种:useContext方法和context提供的Consumer组件
    //Home子组件 使用redux
    import React, { useContext } from 'react';
    import Personale from '../../context';
    
    const Home= () => {
      const personal = useContext(Personale);
      console.log(personal);
      return (
        <Personale.Consumer>
            {value=>{console.log(value)}}
        </Personale.Consumer>
      );
    };
    export default Home;

    两种使用方法打印出来的结果相同:

----------------------------下面是我在一个具体场景中的运用---------------------------

场景:在一个动态生成的多个组件里面,可能一个组件依赖于另一个组件的值而变化

我们首先想到的是redux,这一个可以保存供多个组件使用的解决方案

方法:创建我们自己的reducer,使用useContext提供使用

const { PageData, activeComponent } = useContext(PageContext);

在具体的场景里面,我的PageData存储的页面信息,activeComponent当前选中的页面组件的索引

不出所料,我们果然可以正确使用,

bug:但是,在拉入下一个组件的时候,报错如下

Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement in React Hooks

百度之后https://stackoverflow.com/questions/53472795/uncaught-error-rendered-fewer-hooks-than-expected-this-may-be-caused-by-an-acc发现元问题出现的原因:

我们的组件动态生成是存在判断条件的,也就是通过判断组件的type属性选择对应的组件

switch (type) {
        case 'Array':
            EditorComp = () => {
                return <React.Fragment>{UseArrInput(props, value, handleChange)}</React.Fragment>;
            };
            break;
        case 'Object':
            EditorComp = () => {
                return <React.Fragment>{UseObjectInput(props, value, handleChange)}</React.Fragment>;
            };
            break;
        default:
            EditorComp = () => {
                return <React.Fragment>{Editor(props, value, handleChange)}</React.Fragment>;
            };
            break;
    }

而react的钩子官方要求如下

不要在循环,条件或嵌套函数中调用Hook。相反,始终在React函数的顶层使用Hooks。通过遵循此规则,您可以确保每次组件呈现时都以相同的顺序调用Hook。这就是允许React在多个useStateuseEffect调用之间正确保留Hook状态的原因。

最终解决方案:选择在没有判断条件的顶层使用useContext,将获取的值,作为参数传给组件使用!

原文地址:https://www.cnblogs.com/longlongdan/p/10833412.html