【问题标题】:expand an array in react js在反应js中扩展一个数组
【发布时间】:2017-11-02 09:58:13
【问题描述】:
componentWillMount(){
   this.expand();
  }
componentDidMount(){}
expand(){
var re = [];
this.state.reservation1.length = 9;
  for (var i = 0; i < this.state.reservation1.length; i++) {
     if(this.state.reservation1[i]){
       re[i]=this.state.reservation1[i]
       }
        else {
           re[i]= this.state.reservation1[i]=
              {name:"",active:false,dayindex:0}
            }
        }
   console.log(re)
  console.log(re.dayindex)

   }



constructor(props){
  super(props);
  this.state = {
    reservation1:[
      {name:"8:30",active:true,dayindex:1},
      {name:"jad",active:true,dayindex:3},
      {name:"tony",active:true,dayindex:4},
      {name:"",active:false,dayindex:6},
    ],
    reservations:[]
  };
  this.expand=this.expand.bind(this);
}

返回一个包含 9 个对象的数组 re.dayindex 未定义 有人可以帮忙吗

我正在尝试扩展此数组以按 dayindex 对其重新排序 任何解决方案都会很高兴

【问题讨论】:

  • 还有 reservation1.dayindex 未定义
  • re 是一个数组,因此您也需要将其作为数组访问。 re[0].dayindex
  • 您应该使用setState 在构造函数之外更新状态。你应该not mutate

标签: javascript algorithm reactjs loops


【解决方案1】:

您正在尝试访问数组中的对象。所以应该是re[i].dayindex,我是你的索引。

P.S:你应该尽量不要在 javascript 中改变东西,它确实让你的代码容易受到攻击。 re[i]= this.state.reservation1[i]?

也许你可以试试这个代码:-

const re = [];
const reservation1 = [
      {name:"8:30",active:true,dayindex:1},
      {name:"jad",active:true,dayindex:3},
      {name:"tony",active:true,dayindex:4},
      {name:"",active:false,dayindex:6},
    ];



  reservation1.map((datum,index)=> {
    if (datum) {
      re.push(datum)
    } else {
      re.push({
        name: "",
        active: false,
        dayIndex: 0
      });
    }
  })

  console.log(re[1].dayindex);

【讨论】:

猜你喜欢
  • 2021-06-29
  • 2015-07-13
  • 1970-01-01
  • 2018-01-09
  • 2017-03-20
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多