2017-11-02 1 views
0
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); 
} 

RE ein Array von 9 OBJEKTE re.dayindex undefined reagieren js ist kann bitte jemand helfenein Array erweitern in

ich dieses Array zu erweitern versuche es von dayindex neu zu ordnen wird jede Lösung zufrieden sein

+0

und auch reservation1.dayindex undefiniert – jadlmir

+0

're' ein Array ist, so dass Sie es als ein Array als auch zugreifen müssen. 're [0] .dayindex' – mersocarlin

+0

Sie sollten [setState] (https://reactjs.org/docs/state-and-lifecycle.html#using-state-correctly) verwenden, um den Status außerhalb des Konstruktors zu aktualisieren. Und Sie sollten [nicht mutieren] (https://reactjs.org/docs/optimizing-performance.html#the-power-of-not-mutating-data). –

Antwort

0

Sie versuchen, auf ein Objekt in einem Array zuzugreifen. Also sollte es re[i].dayindex sein, ich bin dein Index.

P.S: Sie sollten versuchen, Dinge in Javascript nicht mutieren, macht es wirklich anfällig für Ihren Code. re[i]= this.state.reservation1[i]?

Vielleicht können Sie diesen Code versuchen: -

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); 
+0

Sorry, ich bin neu bei js, was meinst du mit Mutation – jadlmir

+0

https://medium.com/@fknussel/arrays-objects-and-mutations-6b23348b54aa .. lass es mich wissen, wenn Sie noch etwas brauchen :) –