Reactjs更新状态内数组中的单个元素

时间:2018-04-18 14:57:40

标签: reactjs

我有一个组件:

constructor(props) {
    super(props);

    this.state = {
        cards: []
    };
}

在this.state.cards数组中,对于每张卡,数据结构如下:

{
  movie: v,
  ids: v.id,
  goodDeal: `Cheapest price is ... at ...`
}

现在,我需要将其他卡(比如cards2)数组合并到我当前的state.cards数组中:

componentDidMount(){
    cards2.map((v, i)=>{
       var existedCard = this.state.cards.find((cv, ci)=>{
           if(cv.code === v.code){
               return cv;
           }
       })

       if(existedCard){
          existedCard.ids += v.id;

          this.setState((prevState, pros)=> {
              // then update the state, but how?                   
          })
       }
       else {
          // add the new card into the current cards array
       }
    })
}

如你所见,如果我在card2中找到了一张卡片(newCard),它也在card1(即state.cards)中,那么我将newCard.id添加到existedCard.ids中。 然后我想调用setState()来更新状态。

但是怎么样?

2 个答案:

答案 0 :(得分:1)

使用setState((prevState) => {/* method that returns nextState*/})表格 要添加新对象,请运行

this.setState(prevState => ({
  cards: prevState.cards.concat(existedCard)
}))

对于更新,您必须先过滤旧对象

this.setState(prevState => ({
  cards: prevState.cards.filter( card => card.id !== v.id).concat(existedCard)
}))

如果目标(构建)系统支持扩展运算符,您也可以使用它。

this.setState(prevState => ({
  cards: [...prevState.cards, existedCard]
}))

答案 1 :(得分:1)

Object.assign()是我的解决方案。

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Audio Player Demo</title>
    <meta name="description" content="Demo of the Audio Player jQuery plugin.">
    <meta name="author" content="Jon Bake">
    <link rel="stylesheet" href="src/jquery.audio-player.css">
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>
  <body>
    <div id="audio-player"></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="src/jquery.audio-player.js"></script>
    <script>
      $('#audio-player').audioPlayer();
      //togglePlay
    </script>
    <script>

$(document).ready(function(){
    $("input").keypress(function(){       
// I want to call the function in the src/jquery.audio-player.js
// when the play and pause button is executed with below
// this.$playPause.on("click", this.togglePlay.bind(this));
// How to enable togglePlay() when we keep typing and stoping the typing        
    });
});
</script>

    <input id="target" type="text" value="">
  </body>
</html>