【发布时间】:2021-06-07 13:25:23
【问题描述】:
我想遍历我的jsondata 以删除元素,但我收到以下错误this.state.jsondata is not iterable。我对这个问题有点了解,据我所知,我必须遍历this.state.jsondata 中的项目,但我不知道如何解决它。错误出现在我尝试单独复制jsondata
export default class Success extends React.Component {
constructor(props) {
super();
if (props.location.state) {
this.state = {
jsondata: props.location.state.referrer,
upload: true
} //put jsons data in state object
toast.success('Upload success')
} else {
this.state = {
upload: false
}
}
}
removeData(e) {
console.log(e)
var array = [...this.state.jsondata]; // make a separate copy
var index = e;
if (index !== -1) {
array.splice(index, 1);
this.setState({jsondata: array});
}
}
render() {
const occurrenceMap = Object.values(this.state.jsondata.prediction).reduce((finalMap, item) => {
finalMap[item] = ++finalMap[item] || 1;
return finalMap;
} , {})
console.log(occurrenceMap)
if (!this.state.upload) {
return <Redirect push to={{
pathname: "/"
}}/>
} else return (
<div className="container">
<div className="row">
<Table striped bordered hover>
<thead>
<tr>
<th>#</th>
<th>Label</th>
<th>Text</th>
<th>Prediction</th>
<th>Validation</th>
</tr>
</thead>
<tbody>
{Object.keys(this.state.jsondata.label).map(k =>
<tr>
<td>{k}</td>
<td>{this.state.jsondata.label[k]}</td>
<td>{this.state.jsondata.text[k]}</td>
<td>{this.state.jsondata.prediction[k]}</td>
<td>
<Button variant="success" onClick={() => { alert('Validation') }}>Valider</Button>{' '}
<Button variant="danger" onClick={() => { this.removeData(k) }}>Annuler</Button>
</td>
</tr>
)}
</tbody>
</Table>
</div>
</div>
)
}
}
这里是jsondata:
{label: {…}, text: {…}, prediction: {…}}
label: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}
prediction: {0: 2, 1: 2, 2: 2, 3: 2, 4: 2}
text: {0: "- abc", 1: "abc", 2: "abc", 3: "abc", 4: "abc"}
__proto__: Object
【问题讨论】:
-
this.state.jsondata看起来怎么样?你能粘贴它的样本数据吗?看起来 this.state.jsondata 不是数组。 -
@Shyam 看看编辑
-
所以如果我想删除密钥
1。我应该从label、prediction和text中删除它吗?还是只有label? -
是的,它应该在每个类别中删除,所以如果我想删除键
1它应该从label + prediction + text中删除
标签: arrays json reactjs react-state