update arrays and objects using usestate hook in react
this practical and straightforward article shows you how to properly update objects and arrays in the state in react. we'll use the usestate hook and functional components.
without further ado, let’s get started.
when the state is updated, it is completely overwritten. what if our state is an object with multiple properties, but you only want to change the value of a certain property? for example, we initialize the state of the description box like this:
const [box, setbox] = usestate({
name: 'jiyik.com',
bgcolor: 'blue', // background color
width: 400,
height: 300
});
if you want to change the background color but keep everything else the same, you can use the spread operator (you can also use it with arrays) like this:
setbox(previousstate => {
return { ...previousstate, bgcolor: 'red' }
});
or like this:
setbox({...box, bgcolor: 'red'});
don't use this code:
setbox({bgcolor: 'red'})
because it removes the name, width and height from the state. to make it clearer, let's dive into the working example below.
complete example
app preview
the demo we're going to make shows a box and several form elements. you can update the box's name, background color, width, or height using the corresponding input/select elements.
here’s how it works:
step
following are the steps to build the above demo.
1. create a new react project:
npx create-react-app jiyik-state-example
the name is entirely up to you. choose another one if you wish.
2. final source code in src/app.js (with explanation):
// jiyik.com
// src/app.js
import { usestate } from 'react';
import './app.css';
functionapp() {
// 使用具有四个属性的对象初始化状态
const [box, setbox] = usestate({
name: 'jiyik.com',
bgcolor: 'blue',
width: 400,
height: 100,
});
// 此函数将更新用户在名称字段中键入时将调用的框的名称
const updateboxname = (e) => {
setbox({ ...box, name: e.target.value });
};
// 此函数将更新框的背景颜色,当用户更改选择元素时将调用它
const updatebakcgroundcolor = (e) => {
setbox({ ...box, bgcolor: e.target.value });
};
// 此函数将更新当用户更改宽度输入时将调用的框的宽度
const updateboxwidth = (e) => {
setbox({ ...box, width: parseint(e.target.value) });
};
// 此函数将更新当用户更改高度输入时将调用的框的高度
const updateboxheight = (e) => {
setbox({ ...box, height: parseint(e.target.value) });
};
return (
<div style={{ padding: 30 }}>
{/* 这是盒子 */}
<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>
{/* 这是更改框的表单元素 */}
<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'>blueoption>
<option value='red'>redoption>
<option value='green'>greenoption>
<option value='orange'>orangeoption>
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;
}
export default app;
3. start it:
npm start
and check the result at
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
react.useeffect hook common problems and solutions
publish date:2025/03/11 views:169 category:react
-
大多数开发人员都非常熟悉 react hooks 的工作方式和常见用例,但是有一个 useeffect 问题很多人可能不太清楚。
how to use react lazy code splitting
publish date:2025/03/11 views:104 category:react
-
react lazy 函数允许我们动态导入组件。我们可能希望这样做以减少用户必须下载才能在屏幕上看到内容的初始捆绑包大小。
how to loop over objects in react
publish date:2025/03/11 views:50 category:react
-
在 react 中循环一个对象: 使用 object.keys() 方法获取对象键的数组。 使用 map() 方法遍历键数组。
scroll to bottom of div in react
publish date:2025/03/11 views:169 category:react
-
在 react 中滚动到 div 的底部: 在 div 的底部添加一个元素。 在底部的元素上设置一个 ref。 当事件发生时,调用 ref 对象的 scrollintoview() 方法。
how to draw a horizontal line in react
publish date:2025/03/11 views:73 category:react
-
在 react 中画一条水平线: 使用 hr / 标签并在其上设置 style 属性。 设置线条的高度,并可选择设置背景颜色和颜色。
how to use buttons as links in react
publish date:2025/03/10 views:140 category:react
-
要将按钮用作 react 中的链接,请将按钮包装在 标记中,如果使用 react 路由器,则将其包装在 link 组件中。 该按钮将被呈现而不是链接,单击它将导致浏览器导航到指定的页面。
using onclick on div elements in react
publish date:2025/03/10 views:121 category:react
-
要在 react 中的 div 元素上设置 `onclick` 监听器: 在 div 上设置 `onclick` 属性。 每次单击 div 时,都会调用我们传递给 prop 的函数。 我们可以通过 event.currenttarget 访问 div。
react: how to upload multiple files using axios
publish date:2025/03/10 views:146 category:react
-
这篇简洁明了的文章向您展示了如何在 axios 的帮助下在 react 中上传多个文件。这项工作并不太庞大,可以通过以下几个简单的步骤完成(您将在第 3 步中看到 javascript 和 typescript 代码片
how to toggle a boolean state in react
publish date:2025/03/10 views:93 category:react
-
在 react 中切换布尔状态:使用 usestate 钩子来跟踪布尔值的状态。 将函数传递给钩子返回的 setstate 函数。根据当前值切换布尔值,例如 setisloading(current => !current)。