遇到此问题时,我试图获取一组对象(对不起,我的代码混乱,我是新手)
export class App extends Component {
state ={
character:[]
}
componentDidMount(){
fetch('https://swapi.dev/api/people/').then(data => data.json()).then(res =>{
this.setState(() =>{
const ar = res.results
return {
character: ar
}
})
})
}
render() {
return (
<div>
test
{console.log(this.state.character[0])}
</div>
)
}
}
that code works fine for me at first until i changed the console log to {console.log(this.state.character[0].name)}
it says "cannot read property of an undefined" even though the first line displays the object perfectly