React:使用 useState Hook 更新数组和对象

这篇实用且直截了当的文章向您展示了如何在 React 中正确更新状态中的对象和数组。我们将使用useState钩子和功能组件。

事不宜迟,让我们开始吧。

当状态更新时,它会被完全覆盖。如果您的状态是具有多个属性的对象,但您只想更改某个属性的值怎么办?例如,我们初始化描述框的状态,如下所示:

const [box, setBox] = useState({
   name: 'KindaCode.com',
   bgColor: 'blue', // background color
   width: 400,
   height: 300
});

如果您想更改背景颜色但保持其他内容不变,可以使用扩展运算符(您也可以将其与数组一起使用),如下所示:

setBox(previousState => {
      return { ...previousState, bgColor: 'red' }
});

或者像这样:

setBox({...box, bgColor: 'red'});

不要使用此代码:

setBox({bgColor: 'red'})

因为它会从状态中删除名称、宽度和高度。为了更清楚,让我们深入研究下面的工作示例。

完整的例子

应用预览

我们要制作的演示展示了一个盒子和几个表单元素。您可以使用相应的输入/选择元素来更新框的名称、背景颜色、宽度或高度。

以下是它的工作原理:

React:使用 useState Hook 更新数组和对象

步骤

以下是生成上述演示的步骤。

1.新建一个React项目:

npx create-react-app kindacode-state-example

这个名字完全取决于你。如果您愿意,请选择另一个。

2. src/App.js中的最终源码(附解释):

// KindaCode.com
// src/App.js
import { useState } from 'react';
import './App.css';

function App() {
  // initialize state with an object with four properties
  const [box, setBox] = useState({
    name: 'KindaCode.com',
    bgColor: 'blue',
    width: 400,
    height: 100,
  });

  // this function will update the name of the box
  // it will be called when the user types in the name field
  const updateBoxName = (e) => {
    setBox({ ...box, name: e.target.value });
  };

  // this function will update the background color of the box
  // it will be called when the user changes the select element
  const updateBakcgroundColor = (e) => {
    setBox({ ...box, bgColor: e.target.value });
  };

  // this function will update the width of the box
  // it will be called when the user changes the width input
  const updateBoxWidth = (e) => {
    setBox({ ...box, width: parseInt(e.target.value) });
  };

  // this function will update the height of the box
  // it will be called when the user changes the height input
  const updateBoxHeight = (e) => {
    setBox({ ...box, height: parseInt(e.target.value) });
  };

  return (
    <div style={{ padding: 30 }}>
      {/* Here's the box */}
      <div
        style={{
          width: box.width,
          height: box.height,
          background: box.bgColor,
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
        }}
      >
        <h1 style={{ color: '#fff' }}>{box.name}</h1>
      </div>

      {/* Here's the form elements to change the box */}
      <div
        style={{
          marginTop: 30,
          width: 400,
          display: 'flex',
          flexDirection: 'column',
        }}
      >
        <h3>Change the Apparence of the Box:</h3>
        <p>Box Name:</p>
        <input type='text' value={box.name} onChange={updateBoxName} />

        <p>Background Color:</p>
        <select value={box.bgColor} onChange={updateBakcgroundColor}>
          <option value='blue'>Blue</option>
          <option value='red'>Red</option>
          <option value='green'>Green</option>
          <option value='orange'>Orange</option>
        </select>

        <p>Box Width:</p>
        <input type='number' value={box.width} onChange={updateBoxWidth} />

        <p>Box Height:</p>
        <input type='number' value={box.height} onChange={updateBoxHeight} />
      </div>
    </div>
  );
}

export default App;

3.启动它:

npm start

并在 http://localhost:3000 检查结果。

结论

您已经学习了如何在使用useState挂钩时正确更新状态中的对象和数组。这些知识是必不可少的,不应忘记。