setting and accessing state with dynamic keys in react-ag捕鱼王app官网

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

setting and accessing state with dynamic keys in react

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

use square bracket notation to set and access state in react using dynamic keys, e.g. setemployee({...employee, [key]: employee.salary 100})variables or expressions within the square brackets will be evaluated before the state is set.

import {usestate} from 'react';

const app = () => {
  const [employee, setemployee] = usestate({id: 1, name: 'jiyik', salary: 100});

  const key = 'salary';

  // ✅ 使用动态键访问状态
  console.log(employee[key]); // 👉️ 100

  const handleclick = () => {
    // ✅ 使用动态键设置状态
    setemployee({...employee, [key]: employee.salary   100});
  };

  return (
    <div><buttononclick={handleclick}>increase salarybutton><h2>id: {employee.id}h2><h2>name: {employee.name}h2><h2>salary: {employee.salary}h2>div>
  );
};

export default app;

setting and accessing state with dynamic keys in react

we wrap the dynamic key in square brackets so that it will be evaluated when updating the state.

the key variable will be evaluated as salary and salarythe value of the attribute will be stateupdated in the state object.

请注意, this syntax is not react.js specific, this is pure javascript.

const emp = {id: 2, name: 'bob', salary: 100};

const key = 'salary';

console.log(emp[key]); // 👉️ 100

const newemp = {
  [key]: 200, // 👈️ using dynamic key
};

console.log(newemp); // 👉️ {salary: 200}

we can also use logical or to concatenate strings to form dynamic keys.

const start = 'sal';
const end = 'ary';

const newemp = {
  [start   end]: 200,
};

// 👉️ {salary: 200}

likewise, we can call a function to get the dynamic key.

functiongetkey() {
  return 'salary';
}

const newemp = {
  [getkey()]: 200,
};

console.log(newemp); // 👉️ {salary: 200}

the syntax for setting react component state using dynamic keys is the same.

import {usestate} from 'react';

const app = () => {
  const [employee, setemployee] = usestate({id: 1, name: 'jiyik', salary: 100});

  const handleclick = () => {
    functiongetkey() {
      return 'salary';
    }

    // 👇️ 调用函数获取动态键
    setemployee({...employee, [getkey()]: employee.salary   100});
  };

  return (
    <div><buttononclick={handleclick}>increase salarybutton><h2>id: {employee.id}h2><h2>name: {employee.name}h2><h2>salary: {employee.salary}h2>div>
  );
};

export default app;

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

add an event listener to the body element in react

publish date:2025/03/07 views:131 category:react

向 body 元素添加事件监听器: 访问文档对象上的 body 元素。 在 useeffect 钩子中对 body 元素使用 addeventlistener() 方法。 当组件卸载时移除事件侦听器。 import {useeffect} from react ; export defa

check if an element is in the viewport in react.js

publish date:2025/03/07 views:89 category:react

在 react.js 中检查元素是否在 viewport 中: 在元素上设置 ref 属性。 使用 intersectionobserver api 来跟踪元素是否相交。 app.js import {useeffect, useref, usestate, usememo} from react ; export default function

publish date:2025/03/07 views:161 category:react

要在 react 中按下 enter 键时获取输入的值: 在输入字段上设置 onkeydown 属性。 当用户按下一个键时,检查该键是否为 enter 。 从状态变量访问输入字段的值。 import {usestate} from react ; co

publish date:2025/03/06 views:154 category:react

要使用钩子清除 react 中的 timeout 或 interval: 使用 useeffect 钩子设置超时或间隔。 从 useeffect 钩子返回一个函数。 使用 cleartimeout() 或 clearinterval() 方法删除组件卸载时的超时。、 import

publish date:2025/03/06 views:113 category:react

在 react 中检查一个 prop 是否传递给了一个组件: 将 prop 与 undefined 进行比较。 如果 prop 等于 undefined ,则它不会传递给组件。 否则,它被传递给组件了。 const button = ( {withicon} ) = { if

encountered two children with the same key error in react

publish date:2025/03/06 views:61 category:react

当我们从 map() 方法返回的两个或多个元素具有相同的键属性时,会出现 react 错误 encountered two children with the same key 。 要解决该错误,需要为每个元素的 key prop 提供唯一值或使用 index

export multiple components from a file in react.js

publish date:2025/03/06 views:134 category:react

使用命名导出在 react 中导出多个组件,例如 export function a() {} 和 export function b() {} 。 可以使用命名导入导入导出的组件,如 import {a, b} from ./another-file 。 我们可以在单个文件中根据需

publish date:2025/03/06 views:111 category:react

当我们将不是函数的值传递给元素的 onclick 属性时,会出现错误 expected onclick listener to be a function 。 要解决该错误,请确保仅将函数传递给元素的 onclick 属性。 const app = () = { // ⛔️

publish date:2025/03/06 views:111 category:react

在 react typescript 中将函数作为 props 传递: 在组件的接口中定义函数属性的类型。 在父组件中定义函数。 将函数作为道具传递给子组件。 interface buttonprops { sum : ( a: number , b: number ) =

scan to read all tech tutorials

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

recommended

tags

scan the code
easier access tutorial
网站地图