在 React 中为 useState 设置条件初始值
在 React 中为 useState
设置条件初始值:
- 将函数传递给
useState
钩子。 - 使用条件来确定状态变量的正确初始值。
- 该函数只会在初始渲染时调用。
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。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。