[英]Catch error films.map is not a function in React
I get the catch error or type error on我收到 catch 错误或类型错误
{films.map((film, i) => { ...
can not read proper 'map' or undefined from the Rest Api swapi in React.无法从 React 中的 Rest Api swapi 读取正确的“地图”或未定义。
const api_url_films = 'https://swapi.dev/api/films/'
class Card extends Component {
constructor(props) {
super(props)
this.state = {
films: []
}
this.fetchDataFilms = this.fetchDataFilms.bind(this)
}
fetchDataFilms(){
fetch(api_url_films)
.then(data => (data.json()))
.then(results => {
const api_data = results
this.setState({
films: api_data
})
})
}
componentDidMount() {
this.fetchDataFilms()
}
render() {
const {films} = this.state
return(
<div>
{films.map((film, i) => {
return (
<li key={i}>{film}</li>
)
}
)}
</div>
)
}
}
I try to add in a unordered list also but doesn't work thanks我也尝试添加无序列表,但不起作用,谢谢
I think html is rendered before data is fetched although the films
variable is an empty array in initial state.我认为 html 是在获取数据之前呈现的,尽管films
变量在初始状态是一个空数组。
When films
variable is set from fetching function, html will be re-rendered.当从获取函数中设置films
变量时,将重新渲染 html。
try this code.试试这个代码。 This component will show an empty box until film data is fetched.此组件将显示一个空框,直到获取电影数据。
hope this works!希望这有效!
render() { let films = this.state.films if(films == null || films == []) return <></> return( <div> {films.map((film, i) => { return ( <li key={i}>{film}</li> ) } )} </div> ) }
The response has this shape:响应具有以下形状:
{
count: number,
next: any,
previous: any,
results: Object[], // <-- this is what you want
}
Update the handler to access into the response object and save the results array.更新处理程序以访问响应对象并保存结果数组。
fetchDataFilms(){
fetch(api_url_films)
.then(data => (data.json()))
.then(results => {
const api_data = results
this.setState({
films: api_data.results, // <-- access the results array
})
})
}
Additionally, the film
objects you are mapping are still object, so they are not valid React children.此外,您映射的film
对象仍然是对象,因此它们不是有效的 React 子对象。 You will need to access specific properties.您将需要访问特定属性。
{films.map((film) => {
return (
<li key={film.title}>{film.title}</li> // or director, or producer, etc...
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.