React 中使用动态键设置和访问状态

使用方括号表示法在 React 中使用动态键设置和访问状态,例如 setEmployee({…employee, [key]: employee.salary + 100})。 方括号中的变量或表达式将在设置状态之前进行评估。

import {useState} from 'react';

const App = () => {
  const [employee, setEmployee] = useState({id: 1, name: 'Zadmei', salary: 100});

  const key = 'salary';

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

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

  return (
    <div>
      <button onClick={handleClick}>Increase salary</button>

      <h2>id: {employee.id}</h2>
      <h2>name: {employee.name}</h2>
      <h2>salary: {employee.salary}</h2>
    </div>
  );
};

export default App;

我们将动态键包裹在方括号中,以便在更新状态时对其进行评估。

关键变量将被评估为薪水,salary 属性的值将在 state 态对象中更新。

请注意 ,此语法不是 React.js 特定的,这是纯 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}

我们还可以使用逻辑或连接字符串来形成动态键。

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

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

// ?️ {salary: 200}

同样,我们可以调用一个函数来获取动态键。

function getKey() {
  return 'salary';
}

const newEmp = {
  [getKey()]: 200,
};

console.log(newEmp); // ?️ {salary: 200}

使用动态键设置 React 组件状态的语法是相同的。

import {useState} from 'react';

const App = () => {
  const [employee, setEmployee] = useState({id: 1, name: 'Zadmei', salary: 100});

  const handleClick = () => {
    function getKey() {
      return 'salary';
    }

    // ?️ 调用函数获取动态键
    setEmployee({...employee, [getKey()]: employee.salary + 100});
  };

  return (
    <div>
      <button onClick={handleClick}>Increase salary</button>

      <h2>id: {employee.id}</h2>
      <h2>name: {employee.name}</h2>
      <h2>salary: {employee.salary}</h2>
    </div>
  );
};

export default App;