【发布时间】:2020-12-04 07:17:48
【问题描述】:
没有使用 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>
);
}
}
【问题讨论】:
-
@Naren 我更新了代码请看
标签: javascript reactjs