访问render()方法中的状态值

问题描述 投票:0回答:1

我建立了非常简单的状态如下:

state = {
  nested: Array [
    0: {a:'a'},
    1: {a:'a'}, 
    2: {a:'a'},
    3: {a:'a'}...
  ]
}

nested从远程源(Firebase)获取值。

我已经尝试了3种方法来访问最后一个数组元素的a值:

  1. Object.values(this.state.nested)[Object.values(this.state.nested).length-1].a
  2. Object.values(this.state.nested)[Object.values(this.state.nested).length-1]['a']
  3. Object.values(this.state.nested).map(e=>e.a).pop()

第一和第二种方法在控制台中都可以正常工作,但在React render()方法中给我undefined。 尽管他们返回了我用typeof检查过的嵌套对象,但这一切都已经完成了。

我可以怀疑为什么会这样,但为什么第三种方法有效呢? 我认为这种行为背后有一个原因但却无法想象。

javascript reactjs firebase
1个回答
0
投票

这很可能发生,因为组件在加载数据之前被渲染一次。有两种简单的方法可以解决这个问题:

  1. 在构造函数中为组件设置默认状态
  2. 检查渲染函数以确保嵌套有元素

class ExampleComponent extends React.Component {
  constructor(props) {
    super(props);
    
    //option #1
    state = {
      nested: [{a:'default value'}]
    };
  }
}

要么

class ExampleComponent extends React.Component {
  render() {
    return (
      {
        //option #2
        this.state.nested && this.state.nested.length > 0 ? 
        (//return div using the nested information here ) :
        (//return div in the case nested is empty )
      }
    );
  }
}

如果要在componentDidMount()函数中加载数据,则React将在加载数据后重新呈现组件。一定要在componentDidMount()中使用this.setState()。

© www.soinside.com 2019 - 2024. All rights reserved.