【发布时间】:2017-07-14 00:41:07
【问题描述】:
正如标题所说,我正在尝试渲染一个 React 组件,其中包含我通过使用 fetch() 加载从 JSON 中获取的数据。
api 调用工作正常,但我无法呈现数据。
代码如下:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
user: {}
}
}
getUserById(uId) {
fetch(`https://jsonplaceholder.typicode.com/users/${uId}`)
.then( (response) => {
return response.json()
})
.then( (json) => {
return json;
});
}
componentDidMount() {
this.setState({
user: this.getUserById(4)
})
}
render() {
return (
<div>
<h1>User</h1>
<p>ID: {this.state.user.id}</p>
</div>
);
}
}
ReactDOM.render(
<App/>,
document.getElementById("container")
);
<div id="container"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
有解决这个问题的想法吗?
【问题讨论】:
标签: javascript json ajax reactjs ecmascript-6