我正在一个有4个选项的项目中工作,但每个屏幕只能选择一个选项。该选项将具有ID和分数(基于屏幕)的对象推送到状态中的数组。因此,如果我选择一个并更改为另一个,我希望能够删除前一个对象并将新对象附加到状态为每个屏幕的数组中。如果单击相同的选项,我可以添加和删除对象的脚本,但是我不确定如果做出选择然后立即转到另一个对象,该如何用新对象替换对象。
该数组如下所示:
scores: [
[{id: "G1", score: "4"}, {id: "B1", score: "3"}, {id: "O1", score: "2"}, {id: "R1", score: "1"}],
[{id: "B2", score: "4"}, {id: "G2", score: "3"}, {id: "R2", score: "1"}, {id: "O2", score: "4"}]
]
这是我现在拥有的代码:
handleScore = (id, score, idx) => {
const {
statements,
scores
} = this.state;
if (statements[0][idx].isSelected) {
this.setState({
scores: scores.map((item, index) => index === 0 ? [...item, {
'id': id,
'score': score
}] : item)
});
} else {
this.setState({
scores: scores.map((item, index) => index === 0 ? item.filter(i => i.id !== item[0].id) : item)
});
}
}
并且在render方法中我有:
<div
className={`statement ${(this.state.statements[0][index].isSelected) ? 'selected' : ''}`} key={item.id} onClick={e => {
e.preventDefault();
this.handleScore(item.id, match.params.score, index)
}}>
<a href="#">{item.statement}</a>
</div>
谢谢您!
我不知道您要做什么,但是您可以使用splice()
方法从数组中删除一个项目。选中此repro on Stackblitz以查看结果,如果不起作用,请参见以下代码:
import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";
const App = () => {
const [data, setData] = React.useState([
{id: 0, score:10},
{id: 1, score:20},
{id: 2, score:30},
{id: 3, score:40},
]);
const displayItems = () => {
return data.map((item, index) => {
return (
<div>
<span>id: {item.id}, score: {item.score}</span>{' '}
<button onClick={() => replaceItem(item, index)}>Replace item</button>
</div>
)});
}
const replaceItem = (item, index) => {
const newItem = {id:4, score: 50};
let newData = [...data];
// -----Replace ONE ('1') item at specific index by the newItem
// newData.splice(index, 1, newItem);
// -----OR remove an item and place another at the first index
newData.splice(index, 1); // remove item from array
newData.unshift(item); // Put the item at the first index of the array
//------
setData(newData); // set your newData array as the new state
}
return (
<div>
{displayItems()}
</div>
);
};
render(<App />, document.getElementById("root"));
我放置了两个用例,因此您可以注释/取消注释以查看结果。