我正在尝试通过制作一个简单的应用来学习反应,我试图从服务器获取json格式的数据,然后将其渲染到视图。问题是我收到一个错误,它说this.state.data为null。我该如何解决这个问题?代码:
class App extends React.Component {
constructor() {
super();
//Query data
fetch('http://localhost:8080/api?access_token=56d847accb86bddc243d4b93')
.then(response => response.json())
.then((data) => {
this.setState({
data: data
})
})
.catch(err => console.error('Error ', err.toString()));
}
getInitialState() {
return {
data: {}
};
}
render() {
return (
<h1>{this.state.data}</h1>
);
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
答案 0 :(得分:7)
使用ES6类作为组件时,不会调用getInitialState
方法
而是在构造函数中的实际实例上设置状态。
class App extends React.Component {
constructor() {
super();
this.state = {
data: {}
};
fetch('http://localhost:8080/api?access_token=56d847accb86bddc243d4b93')
.then(response => response.json())
.then(data => this.setState({ data }))
.catch(err => console.error('Error ', err.toString()));
}
render() {
return <h1>{this.state.data}</h1>;
}
}
ReactDOM.render(<App/>, document.getElementById('app'));