关于react.js:React报错之React-Hook-useEffect-is-called-in-function

4次阅读

共计 1938 个字符,预计需要花费 5 分钟才能阅读完成。

注释从这开始~

总览

为了解决谬误 ”React Hook ‘useEffect’ is called in function that is neither a React function component nor a custom React Hook function”,能够将函数名的第一个字母大写,或者应用 use 作为函数名的前缀。比如说,useCounter使其成为一个组件或一个自定义钩子。

这里有个示例用来展现谬误是如何产生的。

// App.js

import React, {useEffect, useState} from 'react';

// 👇️ Not a component (lowercase first letter)
// not a custom hook (doesn't start with use)
function counter() {const [count, setCount] = useState(0);

  // ⛔️ React Hook "useEffect" is called in function "counter" that
  // is neither a React function component nor a custom React Hook function.
  // React component names must start with an uppercase letter.
  // React Hook names must start with the word "use".
  useEffect(() => {console.log(count);
  }, [count]);

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

上述代码片段的问题在于,咱们在一个函数中应用了 useEffect 钩子,而这个函数不是一个组件,因为它以小写字母结尾,也不是一个自定义钩子,因为它的名字不是以 use 结尾。

申明组件

如果你想申明一个组件,请将你的函数的第一个字母大写。

// App.js

import React, {useEffect, useState} from 'react';

// 👇️ is now a component (can use hooks)
function Counter() {const [count, setCount] = useState(0);

  useEffect(() => {console.log(count);
  }, [count]);

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default function App() {
  return (
    <div>
      <Counter />
    </div>
  );
}

函数名必须以大写字母结尾,因为这有助于 React 辨别诸如 pdivspan 等内置元素和咱们定义的组件。

就像文档中所说的:

  • 只从 React 函数组件或自定义钩子中调用 Hook
  • 只在最顶层应用 Hook
  • 不要在循环,条件或嵌套函数中调用 Hook
  • 确保总是在你的 React 函数的最顶层以及任何 return 之前应用 Hook

申明自定义钩子

如果你想申明一个自定义钩子,自定义钩子的名称必须以 use 结尾,比如说useCounter

import React, {useEffect, useState} from 'react';

// 👇️ is a custom hook (name starts with use)
function useCounter() {const [count, setCount] = useState(0);

  useEffect(() => {console.log(count);
  }, [count]);

  return [count, setCount];
}

export default function App() {const [count, setCount] = useCounter();

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

自定义钩子的名字必须以 use 结尾,这样 React 能力辨认你的函数是一个自定义钩子。

总结

为了解决 ”React Hook ‘useEffect’ is called in function that is neither a React function component nor a custom React Hook function” 的谬误,确保只从 React 函数组件或自定义钩子中调用钩子。

正文完
 0