I'm starting with React.js and I'm having trouble accessing nested data in a JSON.
I am using whatwg-fetch
to make the request and it is working, but I can not access the nested data of JSON, eg: data.title
it displays on the screen normally, however data.container.title
it accuses the error:
App.js: 31 Uncaught TypeError: Can not read property 'title' of undefined
I've already looked elsewhere, including the English version of stackoverflow, articles in Portuguese and English, and I have not found an answer, can anyone help me? follows the code and 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"
}
}