繁体   English   中英

如何在 react.js 中更新或添加数组?

[英]How to update or add an array in react.js?

我正在使用本机反应,我的组件基于 class 基础 function。 我在更新或在数组中添加 object 时遇到困难..

我的情况:

我有一个数组:

this.state = {
     dayDeatil:[]
}

现在我想在其中添加一个 obj,但在此之前我想检查 object 是否存在。

obj = { partition :1, day:"sunday","start_time","close_time",full_day:false}

在条件下,如果它们不匹配,我将检查分区和日期。 然后添加一个 object 如果存在然后更新。

这是 function 我正在尝试做那件事。

setTimeFunc =(time)=>{

    try{
    
      console.log("time.stringify() ")

      let obj = {
        partition:this.state.activePartition,
        day:this.state.selectedDay.name,
        full_day:false,
        start_time:this.state.key==="start_time"?time.toString():null
        close_time:this.state.key==="close_time"?time.toString():null
          }

      let day = this.state.dayDetails.filter((item)=>item.day===obj.day&&item.partition===obj.partition)

      if (day.length!==0) {
        day[this.state.key]=time.toString()
        this.setState({...this.state.dayDetail,day})

      } else {
        console.log("2")

        this.setState({
          dayDetails: [...this.state.dayDetails, obj]
        })
      }



      this.setState({ ...this.state, clockVisiblity: false });
    }
    catch(e){
      console.log("error -> ",e)
    }
  }

要检查 object 是否存在,可以使用Array.find()方法,如果不存在,该方法将返回 undefined。

现在要更新 state,更简单的方法是创建一个新数组并将其设置为新的 dayDetails state,如下所示:

const { dayDetails } = this.state;

dayDetails.push(newData);

this.setState({ dayDetails: [...dayDetails] })

您应该在设置 state 时使用扩展运算符,因为 React 在比较组件更新的状态时使用浅比较,所以当您执行 [...dayDetails] 时,您正在为将在 state 上的数组创建新引用,当 React 比较 oldArray === newArray 时,它会改变 UI。

Also, after your else statement, you're updating the state with the state itself, it's good to remember that React state updates are asynchronous, so they won't be availabe right after the setState function call, this may be causing you bugs too .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM