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

Reactjs 如何在componentDidMount()中循环遍历数组?,reactjs,Reactjs,我正在学习更多的ReactJS,并尝试从示例API中显示数据 我可以显示一个标题,但我不知道如何循环数组并显示所有标题 目前我可以显示一个事件标题,例如“Event1”,但我想显示,例如 Event1 Event2 Event3 ... 这是我的app.js: class App extends React.Component { constructor(props) { super(props); this.state = { title:

我正在学习更多的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')
);
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
标题:“”
}
}
componentDidMount(){
var th=这个;
this.serverRequest=
获取(this.props.source)
.then(函数(事件){
塞斯塔({
标题:事件。数据[0]。标题[0]。值
});
})
}
组件将卸载(){
这是.serverRequest.abort();
}
render(){
返回(
在这里,您可以看到一个事件标题:
{this.state.title}
);
}
}
ReactDOM.render(


如何循环数组以显示所有标题,而不是一个?使用map(),或在componentDidMount()中添加for循环?

更改
axios.get
此状态存储从服务器接收的所有数据。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(){
变量标题=[]
this.state.data.forEach(项=>{
titles.push({item.title[0].value})
})
返回(
在这里您可以看到所有标题:)
{titles}
);
}

render(){
返回(
在这里您可以看到所有标题:)
{this.state.data.map(函数(项){
返回{item.title[0].value}
})}
);
}

更改
axios.get
将从服务器收到的所有数据存储在
此.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(){
变量标题=[]
this.state.data.forEach(项=>{
titles.push({item.title[0].value})
})
返回(
在这里您可以看到所有标题:)
{titles}
);
}

render(){
返回(
在这里您可以看到所有标题:)
{this.state.data.map(函数(项){
返回{item.title[0].value}
})}
);
}