我是React的新手,如果我想做一些不能做的事情,我提前道歉。我试图在状态中的 "score "数组中存储一个包含id和分数的选择对象。我在一个名为handleScore的函数中构建了这个对象,当我第一次点击选择并在之后立即将分数数组记录到控制台时,状态似乎显示正确,但当我在渲染方法中将分数数组记录到控制台时,我只是得到一个1。有人知道这是怎么回事吗?下面是代码。
handleScore = (id, score, idx) => {
const { statements, scores } = this.state;
let scoreObj = {};
Object.assign(scoreObj, {'id': id, 'score': score});
if (statements[0][idx].isSelected) {
this.setState({
scores: scores[0].push(scoreObj)
});
console.log("scores array: ", scores[0]); //outputs an array containing [{id: "O1", score: "4"}]
} else {
console.log("scores array: ", scores[0]); // outputs 1
}
}
在render()方法中:
render() {
console.log("this.state.scores from render method: ", this.state.scores); // outputs 1 instead of [{id: "O1", score: "4"}]
return (
<div>
<div className="statements-wrapper">
{
this.state.statements[0].map((item, index) => (
<div
key={item.id} onClick={(e) => {
e.preventDefault();
this.handleScore(item.id, match.params.score, index)
}}>
<a href="#">{item.statement}</a>
</div>
)
)
}
</div>
</div>
)
预期输出:
scores: [
[{id: "O1", score: 4}, {id: "G1", score: 3}, {id: "B1", score: 2}, {id: "R1", score: 1}],
[{id: "O2", score: 4}, {id: "G2", score: 3}, {id: "B2", score: 2}, {id: "R2", score: 1}],
[{id: "O3", score: 4}, {id: "G3", score: 3}, {id: "B3", score: 2}, {id: "R3", score: 1}],
[{id: "O4", score: 4}, {id: "G4", score: 3}, {id: "B4", score: 2}, {id: "R4", score: 1}],
[{id: "O5", score: 4}, {id: "G5", score: 3}, {id: "B5", score: 2}, {id: "R5", score: 1}]
]
我想问题出在替换了全部的 this.state.scores
的时候,将其转换为单个数组。setState
. 为了保存其余的元素数组,你要做一些类似的事情。
handleScore = (id, score, idx) => {
const { statements, scores } = this.state;
if (statements[0][idx].isSelected) {
// this assumes you want to append the first array (hence 'index === 0') in this.state.scores
this.setState({
scores: scores.map((item, index) => index === 0 ? [...item, {'id': id, 'score': score}] : item)
});
}
}
同样重要的是要注意上面的方法以及... push
将把新对象放在 结束 阵列和 setState
是异步的,所以控制台的日志记录 scores
可能不可靠。
要删除一个内部数组中的特定对象,您可以使用 过滤:
// replacing an inner object by id value
scores.map((item, index) => index === 0 ?
item.filter((i) => i.id !== "01")
: item
)