尝试使用函数的结果时出错,typeError:无法读取 React 中未定义的属性'map'



我是React的新手,我已经在下拉列表中列出了电影列表,但我正在尝试从这个json数据中获取名称、年龄和身高并显示它,我想获取电影中出现的所有角色(http://swapi.dev/api/films)并列出名称,性别和身高:这是我从api 中提取的一部电影中的角色列表

"results": [
{
"title": "A New Hope",
"episode_id": 4,

"director": "George Lucas",
"producer": "Gary Kurtz, Rick McCallum",
"release_date": "1977-05-25",
"characters": [
"http://swapi.dev/api/people/1/",
"http://swapi.dev/api/people/2/",
"http://swapi.dev/api/people/3/",
"http://swapi.dev/api/people/4/",
"http://swapi.dev/api/people/5/",
"http://swapi.dev/api/people/6/",
"http://swapi.dev/api/people/7/",
"http://swapi.dev/api/people/8/",
"http://swapi.dev/api/people/9/",
"http://swapi.dev/api/people/10/",
"http://swapi.dev/api/people/12/",
"http://swapi.dev/api/people/13/",
"http://swapi.dev/api/people/14/",
"http://swapi.dev/api/people/15/",
"http://swapi.dev/api/people/16/",
"http://swapi.dev/api/people/18/",
"http://swapi.dev/api/people/19/",
"http://swapi.dev/api/people/81/"
],

然后字符仍然具有/peoples/endpoints

{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "http://swapi.dev/api/planets/1/",
"films": [
"http://swapi.dev/api/films/1/",
"http://swapi.dev/api/films/2/",
"http://swapi.dev/api/films/3/",
"http://swapi.dev/api/films/6/"
],

这是我的代码:

import React, { Component } from 'react'
import Select from 'react-select'
import axios from 'axios'
export default class Contact extends Component {
constructor(props){
super(props)
this.state = {
selectOptions : [],
opening_crawl: "",
title: '',
characters: ''
}
}
async getOptions(){
const res = await axios.get('https://swapi.dev/api/films/')
const data = res.data
const options = data.results.map(d => ({
"value" : d.opening_crawl,
"label" : d.title,
"actors" : d.characters
}))
this.setState({selectOptions: options})
}
handleChange = (e) => {
this.setState({opening_crawl:e.value, title:e.label, characters: e.actors})
}
getCharacters(characters){
const options = characters.map(d => ({
"name" : d.name,
"gender" : d.gender,
"height" : d.height
}))
this.setState({chars: options})
}
debugger;
componentDidMount(){
this.getOptions()
this.getCharacters()
}
render() {
console.log(this.state.selectOptions)
return (
<div>
<Select options={this.state.selectOptions} onChange={this.handleChange} />
<marquee width="1200px" direction="right" height="50px" color='white'>
{this.state.opening_crawl}
</marquee>  
<p>
{this.chars}
</p>
</div>
)
}
}

这行代码得到错误

componentDidMount(){
this.getOptions()
this.getCharacters() // you pass nothing to this function so you got that error
}

最新更新