如何在我的反应应用程序中添加对象到数组

问题描述 投票:0回答:2

我正在学习React并试图创建一个记忆游戏应用程序,在我的应用程序的卡片组件中,如果我点击一张卡片,我想将该卡片推送到一个空阵列。但是如果我点击第二张卡或者它没有正确保存,阵列不会保存第一张卡,因为每次点击一张新卡时道具的值都会改变。我检查了一些类似的问题,但他们发布的问题是不同的。

import React from 'react';
import '../memoryGameStyle/card.css';

class Card extends React.Component{
    constructor(props){
        super(props);
        this.state={card:'' }
    }
    onCardClick=()=>{
        const array=[]
        const newCard={...this.props.card,show:true}
        this.setState({card:newCard})
    }
    render(){...}
}

export default Card

我正在尝试将新卡推送到onCardClick中的阵列。我有两个道具,一个将显示我点击的卡片,另一个将显示所有卡片的阵列。我试图使用filter(),push(),传播运算符,到目前为止非工作,我一定做错了。请帮忙,谢谢

arrays reactjs add react-props
2个回答
0
投票

你是在你的州写的卡变量。这样做

 constructor(props){
    super(props);
    this.state={card:[] }
}

免责声明:以下解决方案假定newCard包含所选卡

onCardClick=()=>{
    const {card} =this.state;
    const newCard= //get selected card
    card.push(newCard);
    this.setState({card:newCard})
}

0
投票

根据我的理解,您有2个要求:

  • 显示当前点击的卡片。
  • 显示用户过去点击过的所有卡片。 //Let me know if that's not the case

假设您要做以上两件事,您可以做以下事情:

state = {
  cards: [],
  showAllClickedCards: true 
}
//"cards" holds the cards clicked by the user
//The most recent clicked card will be at the last in the the array.
//You can toggle "showAllClickedCards" to either show all cards or selected one 

现在,您可以在onCardClick中执行此操作

//Assuming the function is being passed the selectedCard
onCardClick = (selectedCard) => {
     //Do something with selected card
     this.setState(prevState => ({
        cards: [...prevState.cards, selectedCard]
     }))
} 

注意:要显示当前点击的卡,您可以执行this.state.cards[this.state.cards.length - 1]。 希望这可以帮助

© www.soinside.com 2019 - 2024. All rights reserved.