【发布时间】: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