我建立了非常简单的状态如下:
state = {
nested: Array [
0: {a:'a'},
1: {a:'a'},
2: {a:'a'},
3: {a:'a'}...
]
}
nested
从远程源(Firebase)获取值。
我已经尝试了3种方法来访问最后一个数组元素的a值:
Object.values(this.state.nested)[Object.values(this.state.nested).length-1].a
Object.values(this.state.nested)[Object.values(this.state.nested).length-1]['a']
Object.values(this.state.nested).map(e=>e.a).pop()
第一和第二种方法在控制台中都可以正常工作,但在React render()方法中给我undefined
。
尽管他们返回了我用typeof
检查过的嵌套对象,但这一切都已经完成了。
我可以怀疑为什么会这样,但为什么第三种方法有效呢? 我认为这种行为背后有一个原因但却无法想象。
这很可能发生,因为组件在加载数据之前被渲染一次。有两种简单的方法可以解决这个问题:
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()。