【问题标题】:Looping JS object only works with return statement otherwise it throw undefined循环 JS 对象仅适用于 return 语句,否则它会抛出 undefined
【发布时间】:2018-10-18 08:54:20
【问题描述】:

在 JSX 中使用 return 语句的第一个方法可以正常工作

  <div>
    {this.state.list.map(item => {
      return <h6>{item.location.formattedAddress[0]}</h6>
    })}
  </div>

但这通常应该给出相同的结果:

 render() {
    const listItems = this.state.list.map((item, index) => (
        <h6>{item.location.formattedAddress[0]}</h6>
    ));
    return (
      {listItems}
    )
 }

TypeError: 无法读取未定义的属性“地图”

它在加载页面时运行,而不是在执行从 API 加载数据的函数时运行,请有人协助

【问题讨论】:

  • 理想情况下,它们的行为都相同,除非您在 render 方法中有一些东西在 {this.state.list.map(item =&gt; { return &lt;h6&gt;{item.location.formattedAddress[0]}&lt;/h6&gt; })} 执行之前返回
  • 使用return (listItems)删除{})代替return ({listItems}),因为这会返回一个具有listItems属性的对象。其次检查this.state.list,然后再使用map,以防您的状态尚未填充。

标签: javascript reactjs ecmascript-6 jsx


【解决方案1】:

试试这个


这是和你一样的第一种方法:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [
        { id: 1, title: 'React' },
        { id: 2, title: 'Angular' },
        { id: 3, title: 'Vue' }
      ]
    };
  }
  render() {
    return (
      <div>
        {this.state.list && this.state.list.map(li => (
          <h2 key={li.id}>{li.title}</h2>
        ))}
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root">
  <div>

这是您期望它起作用的第二种方法

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [
        { id: 1, title: 'React' },
        { id: 2, title: 'Angular' },
        { id: 3, title: 'Vue' }
      ]
    };
  }
  render() {
    const listItems = this.state.list ? this.state.list.map(li => (
      <h2 key={li.id}>{li.title}</h2>
    )) : '';
    return <div>{listItems}</div>;
  }
}
ReactDOM.render(<App />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"><div>

我在渲染之前添加了一些小检查以确保您不会收到错误:Cannot read property 'map' of undefined

【讨论】:

    【解决方案2】:

    我建议您将 listItems 转换为 renderListItems() 之类的方法,并在映射数组之前添加一个 return。

    renderListItems = () => {
        return this.state.list.map((item, index) => (
            <h6>{item.location.formattedAddress[0]}</h6>
        ));
    }
    

    然后在你的渲染方法中调用它

    render() {
        return (
            <div>
                {this.renderListItems()}
            </div>
        )
    }
    

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      • 2014-08-28
      • 1970-01-01
      • 2011-08-26
      相关资源
      最近更新 更多