在 React 中为 useState 设置条件初始值

在 React 中为 useState 设置条件初始值:

  1. 将函数传递给 useState 钩子。
  2. 使用条件来确定状态变量的正确初始值。
  3. 该函数只会在初始渲染时调用。
import {useState} from 'react';

export default function App() {
  // 👇️ passing function to useState
  const [num, setNum] = useState(() => {
    if (2 * 2 === 4) {
      return 4;
    }

    return 42;
  });

  // 👇️ using a ternary
  const [str, setStr] = useState('hi'.length === 2 ? 'hello world' : 'test');

  return (
    <div>
      <h2>num is: {num}</h2>

      <h2>str is: {str}</h2>
    </div>
  );
}

在第一个示例中,我们将一个函数传递给 useState 钩子。

在第一次渲染期间,num 变量将存储我们从传递给 useState 的回调函数返回的任何内容。

我们可以在函数中使用条件来确定状态变量的正确值。

当初始状态是昂贵计算的结果时,将函数传递给 useState 方法很有用。

我们传递给 useState 的函数只会在初始渲染时被调用。

const [state, setState] = useState(() => {
  const initialState = someExpensiveComputation(props);
  return initialState;
});

这种模式称为惰性初始状态。

如果我们需要一个快速的单行条件来确定初始状态值,可以使用三元运算符。

import {useState} from 'react';

export default function App() {
  // 👇️ using a ternary
  const [str, setStr] = useState('hi'.length === 2 ? 'hello world' : 'test');

  return (
    <div>
      <h2>str is: {str}</h2>
    </div>
  );
}

三元运算符与 if/else 语句非常相似。

如果问号左边的值为真,则运算符返回冒号左边的值,否则返回冒号右边的值。

const result1 = 5 === 5 ? 'yes' : 'no';
console.log(result1); // 👉️ "yes"

const result2 = 5 === 10 ? 'yes' : 'no';
console.log(result2); // 👉️ "no"

如果字符串 hi 的长度为 2 个字符,我们将返回 hello world 作为初始状态值,否则返回 test