setting conditional initial values for usestate in react-ag捕鱼王app官网

current location:home > learning > web front-end > react >

setting conditional initial values for usestate in react

author:jiyik last updated:2025/03/05 views:

to set a conditional initial value for in react usestate:

  1. pass a function to usestatethe hook.
  2. use conditions to determine the correct initial values ​​for state variables.
  3. this function will only be called on the initial render.
import {usestate} from 'react';

export default functionapp() {
  // 👇️ 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>
  );
}

in the first example, we pass a function to usestatethe hook.

during the first render, numthe variable will store usestatewhatever we return from the callback function passed to .

we can use conditionals in functions to determine the correct value for a state variable.

usestatepassing a function to the method is useful when the initial state is the result of an expensive computation .

the function we pass to usestatewill only be called on the initial render.

const [state, setstate] = usestate(() => {
  const initialstate = someexpensivecomputation(props);
  return initialstate;
});

this mode is called lazy initialization.

if we need a quick one-line conditional to determine the initial state value, we can use the ternary operator.

import {usestate} from 'react';

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

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

the ternary operator is if/elsevery similar to the statement.

if the value to the left of the question mark is true, the operator returns the value to the left of the colon, otherwise it returns the value to the right of the colon.

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

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

if the length of the string hi is 2 characters, we will return hello world as the initial state value, otherwise we return test .

for reprinting, please send an email to 1244347461@qq.com for approval. after obtaining the author's consent, kindly include the source as a link.

article url:

related articles

setting default values for input elements in react

publish date:2025/03/05 views:166 category:react

在 react 中为 input 元素设置默认值: 将默认值作为参数传递给受控字段的 usestate 挂钩。 在不受控制的 input 字段上设置 defaultvalue 属性。 import {useref, usestate} from react ; export default functi

publish date:2025/03/05 views:107 category:react

要解决错误 export usehistory was not found in react-router-dom ,请改用 usenavigate 钩子,例如 const navigate = usenavigate() 。 该钩子返回一个函数,允许我们以编程方式导航。 // ?️ import usenavigate

styling the border-radius property in react

publish date:2025/03/05 views:70 category:react

使用 borderradius css 属性来设置 react 中元素的边框半径样式,例如 div style={{border: 1px solid red, borderradius: 30px}} 。 如果我们需要设置特定边框的样式,请使用相应的属性,例如 borderbottom

component definition is missing display name error in react

publish date:2025/03/05 views:133 category:react

在组件上设置 displayname 属性以修复 component definition is missing display name 错误,例如 app.displayname = myapp; 。 或者,禁用带有以下注释的行的 eslint 规则 - // eslint-disable-next-line react/display-na

expected corresponding jsx closing tag error in react

publish date:2025/03/05 views:121 category:react

当我们忘记关闭 jsx 代码中的标签时,会出现 react.js 错误 expected corresponding jsx closing tag 。 要解决错误,请使用自闭标签,例如 input / 并确保 jsx 代码中开始和结束标签的顺序是正确的。

type usestate as array of objects in react typescript

publish date:2025/03/05 views:158 category:react

要在 react 中将 usestate 钩子键入为对象数组,请使用钩子的泛型,例如 const [employees, setemployees] = usestate{salary: number; name: string}[]([]) 。 状态变量可以初始化为一个空数组,并且只接受指

publish date:2025/03/05 views:144 category:react

在 react 中处理 select 元素上的 onchange 事件: 在 select 元素上设置 onchange 属性。 将所选选项的值保存在状态变量中。 每次用户更改所选选项时,更新状态变量。 import {usestate} from react

publish date:2025/03/05 views:73 category:react

在 react 中从数组中为 select 生成 option 标签: 使用 map() 方法迭代数组。 在每次迭代中,返回一个选项元素。 将唯一的关键属性传递给每个选项元素。 const app = () = { const arr = [ { value

publish date:2025/03/05 views:97 category:react

在 react 中使用 onchange 修改文本区域的值: 将 onchange 属性添加到文本区域,将其设置为一个函数。 通过 usestate 钩子将文本区域的值存储在状态中。 每次用户在文本区域中键入时更新状

scan to read all tech tutorials

social media
  • https://www.github.com/onmpw
  • qq:1244347461

recommended

tags

scan the code
easier access tutorial
网站地图