我正在从API提取数据,并且想在屏幕上显示一些对象 (例如“名称”对象),并且出现以下错误:
"TypeError: Cannot read property 'name' of undefined"
我已经尝试在api请求之后显示数据(带有布尔值)
有人知道这可能是什么问题吗?
class App extends Component {
constructor(props) {
super(props)
this.state = {
products: {},
}
this.fetchDevices = this.fetchDevices.bind(this);
}
async fetchDevices() {
const url = 'my url';
const response = await fetch(url, {method : 'GET', headers : headers});
const data = await response.json()
this.setState({products : data.value})
}
componentDidMount() {
this.fetchDevices();
}
render() {
return (
<div>
{this.state.products ? <p>{this.state.products[0].name}</p> : null}
</div>
)}
}
export default App
{
"value": [
{
"urn": null,
"name": "New_COMEC",
"description": null,
"icon": "icon-energy-meter",
"customIdFormat": null,
"customIdDisplay": true,
"customIdRequired": true,
"serialNumberFormat": null,
"serialNumberDisplay": true,
"serialNumberRequired": false,
....,
}
]
答案 0 :(得分:1)
您已将产品状态初始化为空对象而不是数组。 将在您的提取调用之前调用render方法,因此应用程序将中断。 由于您已初始化为对象,
{this.state.products ? <p>{this.state.products[0].name}</p> : null}
在初始渲染中为true,因此当状态实际上是当时的对象时,它会尝试获取第一个数组元素。
您的代码应类似于
class App extends Component {
constructor(props) {
super(props)
this.state = {
products: [],
};
和
{Array.isArray(this.state.products) && this.state.products[0] ? <p>{this.state.products[0].name}</p> : null}