2
I’m starting with React.js and am having trouble accessing data nested in a JSON.
I’m using the whatwg-fetch
to make the request and it’s working, but I can’t access the nested JSON data, example: data.title
it displays on the screen normally though data.container.title
he accuses the error:
App.js:31 Uncaught Typeerror: Cannot read Property 'title' of Undefined
I have looked elsewhere including in the English version of stackoverflow, articles in Portuguese and English and I did not find an answer, can anyone help me? follows the code and the json accessed.
App.js
import React from 'react';
import 'whatwg-fetch';
export default class App extends React.Component {
constructor (props) {
super(props);
this.state = { dados:[] };
}
loadContentFromServer() {
const url = this.props.url;
fetch(url)
.then(response => response.json())
.then(json => {
console.log(json);
this.setState({ dados: json });
});
}
componentDidMount() {
this.loadContentFromServer();
}
render(){
const data = this.state.dados;
return (
<div className="box">
<h1 className="title">
{data.container.title}<br/>
</h1>
</div>
);
}
}
Passing the Json url
index js.
ReactDOM.render(<App url="http://localhost:3232/json/content.json"/>, document.getElementById('app'));
content.json
{
"title": "Titulo",
"numbers": [0, 1, 2, 3],
"container": {
"title": "Titulo",
"content": "conteúdo da página"
}
}
React already calls the render before you make the request on
didMount
and receive the result. Before the request occurs, there is nodata.container.title
, so I think that’s the problem. So try to startdata.container.title
with some other information before– Dherik