【问题标题】:Array object update React SetState [duplicate]数组对象更新React SetState [重复]
【发布时间】:2018-06-26 05:37:30
【问题描述】:

我很困在这里 我有这样的状态

state={
panelData:[ 
             { title:"title"
               content:["one",2] 
             }
          ]         
       }

现在在我的 setState 中我想添加新的标题和内容,也有我之前添加的数据,所以两个对象对吗? 像这样

panelData: [     {title:"title",content:["one",2]} ,
                 {title:"title 2"content:[3,4]}     ]

我试过了

    handlingAddRecipe(){ //this is my update paneldata function
        let contentValue = this.state.recipeContent.join("").split(","); //contentValue = ["content1","content2"]

        this.setState({
          panelData:[{
            title:this.state.recipeTitle,   //title:"title1"
            content:contentValue            //content:contentValue  
          }]
        })
        console.log(this.state.panelData)
  }

我得到的输出没有以前的数据,只有传入面板数据的数据

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:
    this.setState({
              panelData:[...this.state.panelData,{
                title:this.state.recipeTitle,   //title:"title1"
                content:contentValue            //content:contentValue  
              }]
            })
    

    这应该会正确更新

    【讨论】:

    • 非常感谢,我忘了点差运算符... :)
    猜你喜欢
    • 2021-11-11
    • 2018-10-14
    • 2018-02-06
    • 1970-01-01
    • 2018-09-03
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多