javascript无法访问push上的数组方法

时间:2017-10-30 21:34:17

标签: javascript reactjs firebase

我有一个反应应用程序从firebase中提取数据。它将数据添加到数组中。但无法访问。调用索引返回undefined,数组长度为0.但是当你打印数组时,控制台显示里面有一个元素。怎么回事?

componentWillMount() {

    itemsRef.on('value', (snapshot) => {
        let items = snapshot.val();

        let keys = Object.keys(items);

        for(var i = 0; i < keys.length; i += 1) {
            let k = keys[i];
            let name = items[k].name;
            let start = items[k].start;

            this.state.timers.push( {
                name: name,
                start: start
            } );


        }

    });

    console.log(this.state.timers); // shows an array with stuff in it
    this.setState({timers: this.state.timers}); // timers dont get added
    // you cant even access elements in the array.
    // ex: this.state.timers[0] returns undefined, but the console shows that it exists when the whole array is printed.
}

2 个答案:

答案 0 :(得分:1)

你不应该直接进入状态。相反,你应该这样:

ES6变体

const timers = [...this.state.timers];
timers.push({ name, start });
this.setState({ timers })

答案 1 :(得分:1)

你不应该像`this.state.timers.push({})``

那样直接改变你的状态。

你应该做那样的事情:

itemsRef.on('value', (snapshot) => {
  const items = snapshot.val();
  this.setState({
    timers: [
      ...this.state.timers,
      ...Object
        .keys(items)
        .map(key => {
          const { name, start } = items[key];
          return { name, start };
        }),
    ],
  });
});