
前提
javascriptでapiを叩き、ネストされているjsonデータを取得しようとしたら以下のエラーメッセージが出ました。
Uncaught TypeError: Cannot read properties of undefined (reading '0')
at App.render (JSON.js:27:1)
at finishClassComponent (react-dom.development.js:19752:1)
at updateClassComponent (react-dom.development.js:19698:1)
at beginWork (react-dom.development.js:21611:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
ネストされていないデータは問題なく取得できました。
fetchしてきたjsonも、resultsの中身も問題なく取得できています。
以下は取得したいjsonです
{
"count": 327,
"next": "https://pokeapi.co/api/v2/ability/?offset=20&limit=20",
"previous": null,
"results": [
{
"name": "stench",
"url": "https://pokeapi.co/api/v2/ability/1/"
},
{
"name": "drizzle",
"url": "https://pokeapi.co/api/v2/ability/2/"
}
]
}
実現したいこと
ネストされているデータを取得し、ローカルのWebページに表示させる
該当のソースコード
JavaScript
1 2import React, {Component} from "react" 3 4class App extends Component { 5 constructor(){ 6 super() 7 this.state = { 8 loading:false, 9 character:{}, 10 } 11 } 12 13 componentDidMount(){ 14 this.setState({ 15 loading: true 16 }) 17 fetch("https://pokeapi.co/api/v2/ability/") 18 .then(response => response.json()) 19 .then(data => { 20 this.setState({ 21 character: data, 22 loading: false 23 }) 24 }) 25 } 26 27 render() { 28 const displayText = this.state.loading ? "now loading...." : this.state.character.results[0].name 29 //results[0]がundefinedと表示され、displayTextの出力が意図したものにならない 30 31 console.log(this.state.character.results) 32 //こちらは問題なく表示される 33 34 return ( 35 <div> 36 {displayText} 37 </div> 38 ) 39 } 40} 41export default App 42
試したこと
・count、next、previousを取得(成功)
・resultsの全体をconsoleで表示(成功)
・resultsの特定の番目をconsoleで表示(失敗)Uncaught TypeError: Cannot read properties of undefined (reading '特定の番目')


回答2件
あなたの回答
tips
プレビュー