如何在ReactJS中使用setState更新对象
ReactJS允许我们为每个组件定义一个状态对象。在状态对象中,我们可以将不同的变量作为状态对象的属性添加进去。之后,我们可以在组件内部使用状态变量来渲染或执行其他操作。
本教程将教我们为组件创建一个状态对象,并使用不同的值来更新它。
使用setState在ReactJS中更新对象
状态对象在ReactJS中与类组件一起使用。使用setState()方法,我们可以更新状态对象。
语法
用户可以按照以下语法使用setState()方法来更新ReactJS中的对象。
this.setState({
student: {
...this.state.student,
fees: new_value,
},
});
在上面的语法中,我们将更新后的学生对象作为参数传递给setState()方法。同时,我们使用了spread operator与学生对象。
示例
在下面的示例中,我们在类组件中创建了state对象。state对象包含number属性,并使用Math.random()方法初始化为随机数。
每当用户点击按钮时,我们调用changeNumber函数。在changeNumber()函数中,使用setState()方法更新state对象。我们将具有新随机数的对象作为setState()方法的参数传递。
import React, { Component } from "react";
// creating the class component
class App extends Component {
state = {
number: Math.random(),
};
// Method to update the object
changeNumber = () => {
this.setState({ number: Math.random() });
};
render() {
return (
<div>
<h2>
{" "}
Generating the random number and updating it using the{" "}
<i> setState() </i> method.{" "}
</h2>
<h3
style={{
border: "2px solid yellow",
borderRadius: "10px",
width: "22rem",
height: "5rem",
backgroundColor: "blue",
color: "white",
fontSize: "2rem",
}}
>
<span>{this.state.number}</span>
</h3>
<button
onClick= {this.changeNumber}
style = {{
border: "2px solid green",
borderRadius: "10px",
padding: "0.5rem 1rem",
backgroundColor: "yellow",
color: "black",
fontSize: "1rem",
}}
>
{" "}
Generate random values{" "}
</button>
</div>
);
}
}
export default App;
输出
示例
在下面的示例中,table对象包含嵌套对象作为student属性的值。student对象包含id、name、age和fee属性。
然后,每当用户按下按钮时,它调用changesFees()函数,该函数仅更改student对象中fee属性的值。用户可以看到我们如何在setState()方法中使用扩展运算符来保持student对象中其他值不变。
import React, { Component } from "react";
// creating the class component
class App extends Component {
state = {
student: {
id: "123qwe",
name: "Shubham",
age: 22,
fees: 200000,
},
};
// Method to update the object
changeFees = () => {
this.setState({
student: {
...this.state.student,
fees: this.state.student.fees + this.state.student.fees * 0.2,
},
});
};
render() {
return (
<div>
<h2>
{" "}
Updating the fees in the student object using the setState method
<i> setState() </i> method.{" "}
</h2>
<h3
style = {{
border: "2px solid yellow",
borderRadius: "10px",
width: "22rem",
height: "5rem",
backgroundColor: "blue",
color: "white",
fontSize: "2rem",
}}
>
<span> {this.state.student.fees} </span>
</h3>
<button
onClick = {this.changeFees}
style = {{
border: "2px solid green",
borderRadius: "10px",
padding: "0.5rem 1rem",
backgroundColor: "yellow",
color: "black",
fontSize: "1rem",
}}
>
{" "}
Change the fees of student{" "}
</button>
</div>
);
}
}
export default App;
输出
使用ReactJS中的hooks来更新对象的状态
setState()方法是在ReactJS中更新状态对象的一种旧方法。近年来,ReactJS引入了hooks,我们可以使用它们来更新React中的对象或变量值。
语法
用户可以按照以下语法使用hooks来更新状态对象。
const [state, setState] = useState({
prop1: "Value1",
prop2: "value2",
prop3: "value3",
});
setState((state) => ({ ...state, prop3: value }));
以上语法中定义了setState()方法来更新状态对象。在setState()方法中,我们将回调函数作为参数传递进去。
例子
在下面的例子中,我们使用了ReactJS中的函数组件。我们使用状态来存储对象,并使用setState方法来更新状态对象。然而,用户可以为状态和setState给予其他名称。
我们正在接受用户输入作为状态对象的prop3属性的值。然后,我们在handleSubmit()函数中更改状态对象的prop3属性的值。在setState()中,我们将先前的状态作为回调参数获取,并在回调函数中使用它与展开运算符一起使用。
import React, { useState } from "react";
const App = () => {
const [state, setState] = useState({
prop1: "Value1",
prop2: "value2",
prop3: "value3",
});
const [value, setValue] = useState("");
function handleValue(e) {
// handle the value
let new_value = e.target.value;
setValue(new_value);
}
function handleSubmit() {
// updating the state object
setState((state) => ({ ...state, prop3: value }));
}
return (
<div>
<h2>
{" "}
Using the <i> useState hooks </i> to update the objects in the state
</h2>
<h3>Enter the value to change for the prop3 of state object. </h3>
<input type = "text" value = {value} onChange = {handleValue} />
<div style = {{ color: "blue", fontSize: "1.5rem" }}>
The key value pairs of the state object are : prop1 - {state.prop1},
prop2 - {state.prop2}, prop3 - {state.prop3}
</div>
<button
onClick = {handleSubmit}
style = {{
margin: "1rem 0",
padding: "0.5rem 1rem",
backgroundColor: "lightgreen",
border: "2px dotted blue",
borderRadius: "10px",
color: "black",
fontSize: "1.3rem",
padding: "0.5rem",
}}
>
Submit
</button>
</div>
);
};
export default App;
输出
我们学会了在函数组件和类组件中使用setState()方法来更新状态对象。如今,用户可以使用功能组件作为钩子,提供更好的功能来更新状态对象。