首页 > 解决方案 > 如何在组件中使用 react useRef

问题描述

我正在尝试使用上下文来允许所有组件都可以使用身份验证状态。但是我被这个错误难住了

错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。这可能由于以下原因之一而发生:

  1. 你可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 您可能在同一个应用程序中拥有多个 React 副本有关如何调试和修复此问题的提示,请参阅https://reactjs.org/link/invalid-hook-call 。
src/utils/hooks.js:22
  19 | // }, [pokemonName, run])
  20 | const defaultInitialState = { status: "idle", data: null, error: null };
  21 | function useAsync(initialState) {
> 22 |   const initialStateRef = useRef({
  23 |     ...defaultInitialState,
  24 |     ...initialState
  25 |   });```

    UseProvideAuth
src/components/helper/context.js:28
  25 | 
  26 | 
  27 | function UseProvideAuth(props) {
> 28 |   const {
  29 |     data: user,
  30 |     status,
  31 |     error,

    handleSubmit
src/components/login/login-form/index.js:13
  10 | function handleSubmit(event) {
  11 |   event.preventDefault();
  12 |   const { email, password } = event.target.elements;
> 13 |   run(
     | ^  14 |     onSubmit({
  15 |       email: email.value,
  16 |       password: password.value

Index.js

  <React.StrictMode>
    <ProvideAuth>
        <App />
    </ProvideAuth>
  </React.StrictMode>,

ProvideAuth

function ProvideAuth({ children }) {
  return (
    <BrowserRouter>
      <authContext.Provider value={UseProvideAuth}>{children}</authContext.Provider>
    </BrowserRouter>
  );
}

UseProvideAuth

    function UseProvideAuth(props) {
  const {
    data: user,
    status,
    error,
    isLoading,
    isIdle,
    isError,
    isSuccess,
    run,
    setData
  } = useAsync();


useAsync

const defaultInitialState = { status: "idle", data: null, error: null };
function useAsync(initialState) {
  const initialStateRef = useRef({
    ...defaultInitialState,
    ...initialState
  });

Here is a minimal setup on [codesandbox][1] 
Any help would be appreciated.


  [1]: https://codesandbox.io/s/frosty-silence-b0c8i

标签: javascriptreactjsweb-applicationsreact-hooks

解决方案


推荐阅读