【发布时间】:2022-01-19 12:49:44
【问题描述】:
我正在努力将 api 拉到前端。我成功地完成了 https://jsonplaceholder.typicode.com/ 刚刚映射出数组。然而,我正在努力完成我想使用的这个单独的 api
错误是.. "Uncaught TypeError: Cannot read properties of undefined (reading 'results')"
很明显它实际上无法获得结果
我做错了什么?
import React, {Component} from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
list: []
};
}
componentDidMount() {
fetch('https://gateway.marvel.com/v1/public/comics?apikey=3cb62d086d5debdeea139095cbb07fe4&ts=redant&hash=140e85a50884cef76d614f6dacada288')
.then (response => response.json())
.then(users => this.setState({list:users}))
}
render() {
return (
<div className='App'>
{
this.state.list.data.results.map(result =>
<h1 key={result.id}>{result.urls}</h1>
)
}
</div>
)
}
}
export default App
【问题讨论】:
-
首先您将
this.state.list设置为一个空数组,但在render()中您尝试访问this.state.list.data。 array 没有属性data,所以这没有任何意义。fetch和setState也是异步的。当您的组件第一次呈现时,this.state.list将是一个空列表,并且请求只会在组件第一次安装和呈现之后 开始。 -
也不要在关于 SO 的公开访问问题中包含 API 机密。我为你删除了它。如果这是一个敏感的秘密,请从现在开始考虑它已被泄露并尽快更改。