没有使用 setState 更新 JSON 状态
1.我想改变JSON中的特定数量值,为此我写了一个
标记的 IncrementHandler 方法并实现了该功能,但它没有更新我的
主要状态
2.我在函数内部实现了setState方法来更新状态。
import React, { Component } from 'react';
export default class App extends Component {
state = {
value: 0,
students: [
{
item: 'salad',
qty: 2,
department: 'Information Technology',
rollno: '123'
},
{
item: 'cheese',
qty: 2,
department: 'Computer Engineering',
rollno: '456'
},
{
item: 'meat',
qty: 2,
department: 'Information Technology',
rollno: '789'
}
]
};
render() {
const IncrementHandler = (type) => {
if (type === 'salad') {
this.setState((prevState) => ({
qty: this.state.students[0].qty + 1
}));
}
};
return (
<div>
<div>
<div>
<table border="2">
<tbody>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Button</th>
</tr>
{this.state.students.map((item, i) => (
<tr key={i}>
<td>{item.item}</td>
<td>{item.qty}</td>
<td onClick={() => IncrementHandler(item.item)}>click</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
);
}
}
最佳答案
问题
您没有更新 student
中的嵌套状态大批。您正在生成一个新的根状态 key qty
.
this.setState(prevState => ({
qty : this.state.students[0].qty + 1
}))
解决方案浅拷贝
student
array 创建一个新的数组引用,并在数组中浅拷贝要更新的元素。关于在 react 中更新嵌套状态的一般注意事项,您需要浅复制您正在更新的任何对象,因为 React 使用浅对象相等来协调差异。const IncrementHandler = item => {
this.setState(prevState => ({
students: prevState.students.map(student =>
student.item === item
? {
...student,
qty: student.qty + 1,
}
: student,
),
}));
};
注:您可能还应该在渲染函数之外声明此回调。它仍然可以在 render 方法中定义,但它违反了约定。
关于javascript - 如何在 React 中更新 JSON 值数组中的特定值,谁能解释一下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65139388/