如何在componentDidMount()中循环数组?

时间:2016-09-03 18:22:16

标签: reactjs

我正在学习更多ReactJS,并试图从我的示例API中显示数据。

我能够显示一个标题,但我无法弄清楚如何遍历数组,并显示所有标题?

目前我可以显示一个事件标题,例如“Event1”,但我想展示,例如

  Event1
  Event2
  Event3
  ...

这是我的app.js:

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      title: ''
    }
  }

  componentDidMount() {
    var th = this;
    this.serverRequest = 
      axios.get(this.props.source)
        .then(function(event) {    
          th.setState({
            title: event.data[0].title[0].value
          });
        })
  }

  componentWillUnmount() {
    this.serverRequest.abort();
  }

  render() {
    return (
      <div>
        <h1>Here you can see one event title:</h1>
        <h2>{this.state.title}</h2>
      </div>
    );
  }
}

ReactDOM.render(
    <App source="http://localhost:8888/my/api/events" />,
     document.getElementById('container')
);

这是我的index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>App</title>
</head>
<body>

<div id="container"></div>

<script src="https://npmcdn.com/react@15.3.1/dist/react.js"></script>
<script src="https://npmcdn.com/react-dom@15.3.1/dist/react-dom.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
<script type="text/babel" src="js/app.js"></script>

</body>
</html>

以下是我从API获取的数据的console.log():

enter image description here

我怎样才能遍历数组,显示所有标题,而不只是一个?使用map(),或在componentDidMount()中添加for循环?

1 个答案:

答案 0 :(得分:2)

更改axios.get以存储您在this.state.data中收到的所有数据:

axios.get(this.props.source)
     .then(function(event) {    
          th.setState({
            data: event.data
          });
      })

迭代它:

render() {
    var titles = []
    this.state.data.forEach(item => {
       titles.push(<h2>{item.title[0].value}</h2>)
    })
    return (
      <div>
        <h1>Here you can see all titles :)</h1>
        {titles}
      </div>
    );
}

render() {
    return (
      <div>
        <h1>Here you can see all titles :)</h1>
        {this.state.data.map(function(item){
           return <h2>{item.title[0].value}</h2>
         })}
      </div>
    );
}