当我们有条件地使用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); //相关文章
- React中事件的类型定义方式
- React Hook 'useEffect' is called in function报错解
- 解决React报错Expected an assignment or function ca
- 解决React报错JSX element type does not have
- 解决React报错Unexpected default export of anonymou
- 解决React报错Expected `onClick` listener to be
- 解决React报错Encountered two children with the
- 解决React报错Functions are not valid as a React ch
- React中的Hooks路由跳转问题
- 解决React报错Cannot assign to 'current' because it
- 盘点Java中延时任务的多种实现方式