React+Axios-加载的数据可以控制台日志,但不会显示在DOM中



我的简单React应用程序有问题。我可以使用Axios连接到API,并可以控制台日志。但是,我无法在DOM中输出数据。为什么是空的?

import React, { Component } from 'react';
import axios from 'axios';
class App extends Component {
state = {
fragrances: []
}
componentDidMount() {
axios.get('http://localhost:1337/fragrances')
.then(res => {
const fragrances = res.data;
this.setState({ fragrances });
})
}
render() {
const { fragrances }  = this.state;
return (
<div>
{
fragrances.map((fragrance, index) => {
<h2>{fragrance.Name}</h2>
console.log(fragrance);
})
}
</div>
);
}
}
export default App;

您没有从map返回任何内容

应该是

fragrances.map((fragrance, index) => { 
return Boolean(fragrance.Name) && <h2 key={index}>{fragrance.Name}</h2>  
})

如注释中所述,在返回组件列表时需要使用键。这里我使用index,但这是一种糟糕的做法(阅读https://reactjs.org/docs/lists-and-keys.html#keys(。希望您的fragrance对象有一个唯一的id,这是您应该使用的。

最新更新