亲宝软件园·资讯

展开

React hook 'useState' is called conditionally报错解决

Borislav Hadzhiev 人气:0

总览

当我们有条件地使用useState钩子时,或者在一个可能有返回值的条件之后,会产生"React hook 'useState' is called conditionally"错误。为了解决该错误,将所有React钩子移到任何可能油返回值的条件之上。

这里有个例子用来展示错误是如何发生的。

import React, {useState} from 'react';
export default function App() {
  const [count, setCount] = useState(0);
  if (count > 0) {
    return <h1>Count is greater than 0</h1>;
  }
  // ⛔️ React Hook "useState" is called conditionally.
  //React Hooks must be called in the exact same order
  // in every component render. Did you accidentally call
  // a React Hook after an early return?
  const [message, setMessage] = useState('');
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

上述代码片段的问题在于,我们使用的第二个useState钩子,位于可能有返回值的条件之后。

顶层调用

为了解决该问题,我们必须在最顶层调用React钩子

import React, {useState} from 'react';
export default function App() {
  const [count, setCount] = useState(0);
  // 

加载全部内容

相关教程
猜你喜欢
用户评论