【问题标题】:React Hook "useCreateContext" cannot be called at the top level无法在顶层调用 React Hook “useCreateContext”
【发布时间】:2021-05-23 05:20:01
【问题描述】:

我正在编写一个 React 登录页面,但出现以下错误:

4:40 错误 React Hook "useCreateContext" 不能在顶层调用。必须在 React 函数组件或自定义 React Hook 函数中调用 React Hooks
反应钩子/钩子规则

这是可能导致问题的代码。

import React, { useContext, createContext } from 'react';

export function useCreateContext(defaultValue, reducer) {
  const defaultDispatch = () => defaultValue;
  const stateCtx = createContext(defaultValue);
  const dispatchCtx = createContext(defaultDispatch);

  function useStateCtx(property) {
    const state = useContext(stateCtx);
    return state[property]; // only one depth selector for comparison
  }

  function useDispatchCtx() {
    return useContext(dispatchCtx);
  }

  function Provider({ children }) {
    const [state, dispatch] = React.useReducer(reducer, defaultValue);
    return (
      <dispatchCtx.Provider value={dispatch}>
        <stateCtx.Provider value={state}>{children}</stateCtx.Provider>
      </dispatchCtx.Provider>
    );
  }
  return [useStateCtx, useDispatchCtx, Provider];
}


export const initialState = {
  isSticky: false,
  isSidebarSticky: true,
};

export function reducer(state, { type }) {
  switch (type) {
    case 'SET_STICKY':
      return {
        ...state,
        isSticky: true,
      };
    case 'REMOVE_STICKY':
      return {
        ...state,
        isSticky: false,
      };
    case 'SET_SIDEBAR_STICKY':
      return {
        ...state,
        isSidebarSticky: true,
      };
    case 'REMOVE_SIDEBAR_STICKY':
      return {
        ...state,
        isSidebarSticky: false,
      };
    default: {
      throw new Error(`Unsupported action type: ${type}`);
    }
  }
}

const [state, useDispatch, provider] = useCreateContext(initialState, reducer);

export const useStickyState = state;
export const useStickyDispatch = useDispatch;
export const StickyProvider = provider;


然后我在首页使用 StickProvider。

export default function IndexPage() {
  return (
    <StickyProvider>
      <Layout>
        <SEO title="Startup Landing 005" />
        <Banner />
        <KeyFeature />
        <ServiceSection />
        <Feature />
        <CoreFeature />
        <WorkFlow />
        <Package />
        <TeamSection />
        <TestimonialCard />
        <BlogSection />
        <Subscribe />
      </Layout>
    </StickyProvider>
  );
}

谁能帮忙解决这个错误?

【问题讨论】:

  • 这不是一个钩子,所以不要使用use 前缀

标签: reactjs react-hooks


【解决方案1】:

你必须调用它 const [state, useDispatch, provider] = useCreateContext(initialState, reducer); 在函数内部而不是外部你正在打破钩子规则。 你做外部功能的方式是错误的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-07
    • 2022-10-14
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多