React报错之Rendered more hooks than during the previo

2024-05-16 14:49:11 浏览数 (2)

正文从这开始~

总览

当我们有条件地调用一个钩子或在所有钩子运行之前提前返回时,会产生"Rendered more hooks than during the previous render"错误。为了解决该错误,将所有的钩子移到函数组件的顶层,以及不要在条件中使用钩子。

React报错之Rendered more hooks than during the previoReact报错之Rendered more hooks than during the previo

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

代码语言:javascript复制
// App.js

import {useEffect, useState} from 'react';

export default function App() {
  const [counter, setCounter] = useState(0);

  // ⛔️ Error: Rendered more hooks than during the previous render.
  if (counter > 0) {
    // 


	

0 人点赞