如何在 React 中切换布尔状态

在 React 中切换布尔状态:

  1. 使用 useState 钩子来跟踪布尔值的状态。
  2. 将函数传递给钩子返回的 setState 函数。
  3. 根据当前值切换布尔值,例如 setIsLoading(current => !current)
import {useState} from 'react';

export default function App() {
  // ?️ initialize boolean to false
  const [isLoading, setIsLoading] = useState(false);

  const toggleIsLoading = () => {
    // ?️ passed function to setState
    setIsLoading(current => !current);
  };

  return (
    <div>
      <button onClick={toggleIsLoading}>Toggle loading state</button>
      {isLoading && <h2>Loading...</h2>}
    </div>
  );
}

如何在 React 中切换布尔状态

我们向 setIsLoading 传递了一个函数,因为保证使用 isLoading 布尔值的当前(最新)值调用该函数。

在示例中,我们简单地切换布尔值并返回结果以更新状态。

我们使用逻辑 NOT (!) 运算符来翻转布尔值。

以下是使用逻辑非运算符的一些示例。

console.log(!true); // ?️ false console.log(!false); // ?️ true

注意 ,我们不应尝试在更改布尔状态变量后立即访问它。

如果我们在使用 setIsLoading 函数更新后立即尝试访问 isLoading 状态变量,则无法保证我们将获得当前(最新)值。

如果我们需要监听状态变化,请将状态变量添加到 useEffect 挂钩的依赖项数组中。

import {useEffect, useState} from 'react';

export default function App() {
  const [isLoading, setIsLoading] = useState(false);

  const toggleIsLoading = () => {
    // ?️ passed function to setState
    setIsLoading(current => !current);
  };

  useEffect(() => {
    // ?️ 如果我们需要监听 isLoading 布尔值的变化
    console.log('isLoading is: ', isLoading);
  }, [isLoading]);

  return (
    <div>
      <button onClick={toggleIsLoading}>Toggle loading state</button>
      {isLoading && <h2>Loading...</h2>}
    </div>
  );
}

我们将 isLoading 状态变量添加到钩子的依赖项数组中,所以任何时候 isLoading 发生变化,我们的 useEffect 钩子中的逻辑都会重新运行。

注意 ,挂载组件时也会调用该钩子。

如果我们不想在初始渲染时运行 useEffect 挂钩中的逻辑,但仅在特定状态变量更改时,请使用 ref 在初始渲染时提前返回。

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

export default function App() {
  const [isLoading, setIsLoading] = useState(false);

  const toggleIsLoading = () => {
    setIsLoading(current => !current);
  };

  const isFirstRender = useRef(true);

  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
      return; // ?️ return early if first render
    }

    console.log('isLoading is: ', isLoading);
  }, [isLoading]);

  return (
    <div>
      <button onClick={toggleIsLoading}>Toggle loading state</button>
      {isLoading && <h2>Loading...</h2>}
    </div>
  );
}

当在 mount 上运行 useEffect 钩子时,我们使用 ref 提前退出。

如果我们想监听状态变化但需要跳过第一次渲染,请使用此方法。