useContext的使用

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

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

方法:建立咱们本身的reducer,使用useContext提供使用ide

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

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

不出所料,咱们果真能够正确使用,this

bug:可是,在拉入下一个组件的时候,报错以下spa

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发现元问题出现的缘由:code

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

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状态的缘由。ci

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

相关文章
相关标签/搜索