Reactjs 在react组件中映射API数据-如何访问特定属性?
我想返回一个列表,其中包含来自以下(截断的)API响应的名称值:Reactjs 在react组件中映射API数据-如何访问特定属性?,reactjs,fetch,Reactjs,Fetch,我想返回一个列表,其中包含来自以下(截断的)API响应的名称值: { "count": 82, "next": "http://swapi.dev/api/people/?page=2", "previous": null, "results": [ { "name": "Luke Skywalk
{
"count": 82,
"next": "http://swapi.dev/api/people/?page=2",
"previous": null,
"results": [
{
"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": [
我希望在以下组件中返回名称数据:
class App extends React.Component {
constructor(){
super()
this.state = {
characterName:''
}
}
componentDidMount() {
fetch('https://swapi.dev/api/people/')
.then(res => res.json())
.then(data => {
this.setState({
characterName: data
})
})
}
render() {
return(
<div>
<h1>heading</h1>
<p>{this.state.characterName.results.map(person => {
return ...person.name
})
}
<p/>
</div>
)
}
}
类应用程序扩展了React.Component{
构造函数(){
超级()
此.state={
字符名:“”
}
}
componentDidMount(){
取('https://swapi.dev/api/people/')
.then(res=>res.json())
。然后(数据=>{
这是我的国家({
字符名称:数据
})
})
}
render(){
返回(
标题
{this.state.characterName.results.map(person=>{
return…person.name
})
}
)
}
}
我只想呈现一个名称列表,如何更改映射函数来实现这一点?谢谢首先,您需要将状态中的
characterName
键初始值更新为数组
this.state={
字符:[]
}
接下来,将字符的值设置为数据。结果
this.setState({
字符:data.results
})
然后像这样映射字符数组
标题
{this.state.characters.map((char)=>{char.name})}