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

目录
  • 总览
  • 顶层调用

总览

当我们有条件地使用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);
  // ️ move hooks above condition that might return
  const [message, setMessage] = useState('');
  // ️ any conditions that might return must be below all hooks
  if (count > 0) {
    return <h1>Count is greater than 0</h1>;
  }
  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);
  if (count === 0) {
    // ️ React Hook "useState" is called conditionally.
    // React Hooks must be called in the exact same order in every component render.
    const [message, setMessage] = useState('');
  }
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

上面的代码片段导致了错误,因为我们有条件地调用第二个useState钩子。

这是不允许的,因为钩子的数量和钩子调用的顺序,在我们的函数组件的重新渲染中必须是相同的。

为了解决这个错误,我们必须把useState的调用移到顶层,而不是有条件地调用这个钩子。

就像文档中所说的:

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

原文链接:bobbyhadz.com/blog/react-…

以上就是React hook 'useState' is called conditionally报错解决的详细内容,更多关于React报错useState conditionally的资料请关注我们其它相关文章!

(0)

相关推荐

  • 解决React报错Parameter 'props' implicitly has an 'any' type

    目录 总览 安装类型文件 声明类型 泛型 重新安装 总览 当我们没有为函数组件或者类组件的props声明类型,或忘记为React安装类型声明文件时,会产生"Parameter 'props' implicitly has an 'any' type"错误.为了解决这个错误,在你的组件中明确地为props对象设置一个类型. 安装类型文件 你首先要确定的是你已经安装了React类型声明文件.在项目的根目录下打开终端,并运行以下命令. # ️ with NPM npm install --s

  • 解决React报错You provided a `checked` prop to a form field

    目录 总览 defaultChecked onChange 初始值 总览 当我们在多选框上设置了checked 属性,却没有onChange 处理函数时,会产生"You provided a checked prop to a form field without an onChange handler"错误.为了解决该错误,可以使用defaultChecked 属性,或者在表单字段上设置onChange 属性. 这里有个例子用来展示错误是如何发生的. // App.js export

  • 解决React报错Property does not exist on type 'JSX.IntrinsicElements'

    目录 总览 组件大写 类型声明 总结 总览 当组件名称以小写字母开头时,会导致"Property does not exist on type 'JSX.IntrinsicElements'"错误.为了解决该错误,确保组件名称总是以大写字母开头,安装React声明文件并重启你的开发服务器. 这里有个示例用来展示错误是如何发生的. // App.tsx // ️ name starts with lowercase letter function myComponent() { retu

  • 解决React hook 'useState' cannot be called in a class component报错

    目录 总览 函数组件 类组件中使用setState() 总览 当我们尝试在类组件中使用useState 钩子时,会产生"React hook 'useState' cannot be called in a class component"错误.为了解决该错误,请将类组件转换为函数组件.因为钩子不能在类组件中使用. 这里有个例子用来展示错误是如何发生的. // App.js import {useState, useEffect} from 'react'; class Example

  • 解决React报错Rendered more hooks than during the previous render

    目录 总览 顶层调用 条件之上 总览 当我们有条件地调用一个钩子或在所有钩子运行之前提前返回时,会产生"Rendered more hooks than during the previous render"错误.为了解决该错误,将所有的钩子移到函数组件的顶层,以及不要在条件中使用钩子. 这里有个示例用来展示错误是如何发生的. // App.js import {useEffect, useState} from 'react'; export default function App

  • 解决React报错Invalid hook call

    目录 总览 版本匹配 调用组件 总览 导致"Invalid hook call. Hooks can only be called inside the body of a function component"错误的有多种原因: react和react-dom的版本不匹配. 在一个项目中有多个react包版本. 试图将一个组件作为一个函数来调用,例如,App()而不是<App />. 在类里面使用钩子,或者在不是组件或自定义钩子的函数中使用钩子. 版本匹配 在项目的根目录

  • 解决React报错React Hook useEffect has a missing dependency

    目录 总览 禁用规则 依赖移入 依赖移出 useMemo useCallback 总览 当useEffect钩子使用了一个我们没有包含在其依赖数组中的变量或函数时,会产生"React Hook useEffect has a missing dependency"警告.为了解决该错误,禁用某一行的eslint规则,或者将变量移动到useEffect钩子内. 这里有个示例用来展示警告是如何发生的. // App.js import React, {useEffect, useState}

  • 解决React报错Cannot find namespace context

    目录 总览 tsx 安装@types/包 手动添加 总览 在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig.json文件中把jsx设置为react-jsx,并确保为你的应用程序安装所有必要的@types包. 这里有个例子来展示错误是如何发生的. // App.ts import React from 'react'; interface UserCtx { first: stri

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

    目录 总览 顶层调用 总览 当我们有条件地使用useState钩子时,或者在一个可能有返回值的条件之后,会产生"React hook 'useState' is called conditionally"错误.为了解决该错误,将所有React钩子移到任何可能油返回值的条件之上. 这里有个例子用来展示错误是如何发生的. import React, {useState} from 'react'; export default function App() { const [count,

  • React Hook 'useEffect' is called in function报错解决

    目录 总览 声明组件 声明自定义钩子 总结 总览 为了解决错误"React Hook 'useEffect' is called in function that is neither a React function component nor a custom React Hook function",可以将函数名的第一个字母大写,或者使用use作为函数名的前缀.比如说,useCounter使其成为一个组件或一个自定义钩子. 这里有个示例用来展示错误是如何发生的. // App.j

  • Objects are not valid as a React child报错解决

    目录 总览 map JSON.stringify Date 花括号 async 总结 总览 当我们尝试在JSX代码中,直接渲染对象或者数组时,会产生"Objects are not valid as a React child"错误.为了解决该错误,在JSX代码中,使用map()方法来渲染数组或者访问对象的属性. 下面是错误如何发生的示例. export default function App() { const employees = [ {id: 1, name: 'Alice'

  • React报错解决之ref返回undefined或null

    目录 总览 useEffect 事件 总结 总览 当我们试图在其对应的DOM元素被渲染之前访问其current属性时,React的ref通常会返回undefined或者null.为了解决该问题,可以在useEffect钩子中访问ref,或者当事件触发时再访问ref. import {useRef, useEffect} from 'react'; export default function App() { const ref = useRef(); console.log(ref.curre

  • 详解BadTokenException报错解决方法

    线上出现了如上的 crash,第一解决反应是在 show dialog 之前做个 isFinish 和 isDestroyed 判断,当我翻开代码正要解决时,我惊了,原来已经做过了如上的判断检测,示例伪代码如下: public void showDialog(Activity activity){ new OkHttp().call(new Callback(){ void onSucess(Response resp){ if(activity!=null && !activity.is

  • SpringMail使用过程中的报错解决办法

    SpringMail使用过程中的报错解决办法 1.Unable to locate provider for protocol: smtp –>缺少依赖造成的 <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency> <dependency

  • IntelliJ IDE运行Tomcat报错解决办法

     IntelliJ IDE运行Tomcat报错解决办法 由于Tomcat默认关闭JMX功能,但IntelliJ IDE配置的IDE需要提供JMX功能,所以IntelliJ IDE运行Tomcat报错:Unable to ping server at localhost:1099! 解决的办法: 1.为Tomcat开启JMX功能,比较麻烦. 2.不使用JMX功能,修改host文件: 127.0.0.1 localhost [添加计算机名] 例如我的计算机名为Linux,所以设置为 127.0.0.

  • Linux 初始化MySQL 数据库报错解决办法

     Linux 初始化MySQL 数据库报错解决办法 在Linux   CentOS 5 中安装完MySQL (server.devel)之后进行初始化 service mysqld  start ,执行命令报错: Neither host 'localhost.localdomain' nor 'localhost' could be looked up with /usr/bin/resolveip Please configure the 'hostname' command to retu

  • php安装扩展mysqli的实现步骤及报错解决办法

    php安装扩展mysqli的实现步骤及报错解决办法 terminal #cd php-5.3.6/ext/mysqli #/usr/local/webserver/php/bin/phpize #./configure --with-php-config=/usr/local/webserver/php/bin/php-config #make #make instal 报错: checking for MySQLi support... yes checking whether to enab

随机推荐