如何更新 ReactJS 中的嵌套状态属性?
有以下方法可以更新 ReactJS 中的嵌套状态属性:
- 方法 1:我们可以创建一个虚拟对象来对其执行操作(更新我们想要的属性),然后用更新的对象替换组件的状态。
- 方法 2 :我们可以使用扩展运算符传递旧的嵌套对象,然后覆盖嵌套对象的特定属性。
创建反应应用程序:
第 1 步:使用以下命令创建一个 React 应用程序:
npx create-react-app foldername
第 2 步:创建项目文件夹(即文件夹名称)后,使用以下命令移动到该文件夹:
cd foldername
项目结构:它将如下所示。
方法一:App.js
Javascript
import React, { Component } from "react";
class App extends Component {
// Nested object
state = {
name: 'kapil',
address: {
colony: 'vaishnav nagar',
city: 'Jaipur',
state: 'Rajasthan'
}
};
handleUpdate = () => {
// Creating a dummy object using spread operator
var address = { ...this.state.address }
// Updating the city
address.city = 'Kota';
this.setState({ address })
}
render() {
return (
{this.state.name}
{this.state.address.colony} {","}
{this.state.address.city}{", "}
{this.state.address.state}
);
}
}
export default App;
Javascript
import React, { Component } from "react";
class App extends Component {
// Nested object
state = {
name: 'kapil',
address: {
colony: 'vaishnav nagar',
city: 'Jaipur',
state: 'Rajasthan'
}
};
handleUpdate = () => {
// Overriding the city property of address object
this.setState({ address: { ...this.state.address, city: "kota" } })
}
render() {
return (
{this.state.name}
{this.state.address.colony} {","}
{this.state.address.city}{", "}
{this.state.address.state}
);
}
}
export default App;
方法 2:App.js
Javascript
import React, { Component } from "react";
class App extends Component {
// Nested object
state = {
name: 'kapil',
address: {
colony: 'vaishnav nagar',
city: 'Jaipur',
state: 'Rajasthan'
}
};
handleUpdate = () => {
// Overriding the city property of address object
this.setState({ address: { ...this.state.address, city: "kota" } })
}
render() {
return (
{this.state.name}
{this.state.address.colony} {","}
{this.state.address.city}{", "}
{this.state.address.state}
);
}
}
export default App;
运行应用程序的步骤:从项目的根目录使用以下命令运行应用程序:
npm start
输出: