Arrays 通过单击React将元素添加到数组中
我想通过单击div元素来创建一个数组。这是产品的一张卡片Arrays 通过单击React将元素添加到数组中,arrays,reactjs,Arrays,Reactjs,我想通过单击div元素来创建一个数组。这是产品的一张卡片 class Card extends Component { constructor(props){ super(props) this.state = { likesArr: [] } } // toggle for changing handleClick = (e) => { e.preventDefault(); //toggle div to the
class Card extends Component {
constructor(props){
super(props)
this.state = {
likesArr: []
}
}
// toggle for changing
handleClick = (e) => {
e.preventDefault();
//toggle div to the favorite
this.setState(prevState => {
return { liked: !prevState.liked }
})
//creating an array
let likesArr = this.state.likesArr;
let newLike = e.currentTarget.id; // get product's id
likesArr.push(newLike);
// option 1
this.setState(previousState => ({
likesArr: [...previousState.likesArr, newLike]
}));
// option 2
// this.setState({
// likesArr:[...this.state.likesArr, newLike]
// });
console.log(likesArr);
}
return (
...
<div className="liked" onClick={this.handleClick} id={product.id}>
{product}
</div>
...
)}
类卡扩展组件{
建造师(道具){
超级(道具)
this.state={
likesArr:[]
}
}
//切换以进行更改
handleClick=(e)=>{
e、 预防默认值();
//将div切换到收藏夹
this.setState(prevState=>{
返回{liked:!prevState.liked}
})
//创建数组
让likesArr=this.state.likesArr;
让newLike=e.currentTarget.id;//获取产品的id
likesArr.push(newLike);
//选择1
this.setState(previousState=>({
likesArr:[…previousState.likesArr,newLike]
}));
//选择2
//这是我的国家({
//likesArr:[…this.state.likesArr,newLike]
// });
console.log(像sarr);
}
返回(
...
{product}
...
)}
所以问题是我只得到最后一个产品id为的空数组
[“577922”]
,如果我设置初始数组[“1”],我会得到(2)[“1”,“577922”]
,但不是新数组
有什么建议吗
更新:
添加了//创建数组
让likesArr=this.state.likesArr;
/* ... */
likesArr.push(newLike);
这是错误的。您正在获取对处于状态的数组的引用并对其进行变异
您需要先克隆阵列。您可以使用slice()
来实现这一点:
让newLike=e.currentTarget.id;//获取产品的id
this.setState(previousState=>{
让newLikesArr=previousState.likesArr.slice();//谢谢你的努力,但你的两个选项都给出了与我相同的结果。你能用你的代码创建一个代码笔让我看看吗?likesArr应该包含什么?所有喜欢的产品的列表?在这种情况下,它不应该是产品,而是应用程序的状态。