简体   繁体   English

在React中使用数组键迭代状态对象

[英]Iterate loop over state object with an array key in React

I have a function getBar() returning an object like: 我有一个函数getBar()返回如下对象:

{
  foo: 'value',
  array: ['a', 'b', 'c']
}

Here's my React component calling the above function ie getBar() : 这是我的React组件,调用上述函数,即getBar()

class foo extends Component {

  state = {
    bar: {}
  };    
  componentDidMount(){
    this.setState({
      bar : getBar()
    });
  }
  render() {
    {this.state.bar.array.map((value, i) => <div class="row" key={i}>{value}</div>)}
  }
}

It always gives me Uncaught TypeError: Cannot read property 'map' of undefined error. 它总是给我带来Uncaught TypeError: Cannot read property 'map' of undefined错误的Uncaught TypeError: Cannot read property 'map' of undefined Exploring similar questions , I came to know I will have to declare an empty state array which I did in different ways but none worked. 通过研究类似的问题 ,我知道必须声明一个空状态数组,该数组以不同的方式执行,但没有任何作用。 Can anybody please give me an appropriate answer preferably with complete logic. 任何人都可以最好地以完整的逻辑给我一个适当的答案。

I tried another way of declaring the state array to a const in render() but didn't get successful results. 我尝试了另一种在render()中将状态数组声明为const ,但未获得成功的结果。

Ok, so this is actually something to do with your component's lifecycle 好的,所以这实际上与组件的生命周期有关

The problem is that your render method runs before the componentDidMount method. 问题是您的render方法在componentDidMount方法之前运行。 So the first time your component renders your state looks like this: 因此,组件第一次呈现状态时如下所示:

{
  bar: {},
}

So no array property on bar, which means you cannot map over it (which is why you get errors 😣). 因此,bar上没有数组属性,这意味着您无法对其进行映射(这就是为什么会出现错误errors)。 Instead you could use the componentWillMount method, to set the state before the render method runs, or you could do a check on array being set before mapping over it. 相反,您可以使用componentWillMount方法在运行render方法之前设置状态,或者可以在映射之前对设置的数组进行检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM