我设置了一个 rest API 后端。我想在组件的 getInitialState
函数内设置值,但我不知道如何填充我需要返回的对象,因为我使用的是异步 http 请求。正如预期的那样,我返回的对象具有未定义的值。我该如何解决这个问题?
我现在正在使用 fetch(老实说,可以切换到任何其他库)。我不知道如何在异步调用返回某个值之后而不是在它发生之前调用 getInitialState
。
import React from 'react';
import 'whatwg-fetch';
export default class IndexPage extends React.Component {
render() {
// I basically need to call getInitialState after the last promise has been resolved
fetch('https://localhost:3000/api/aye')
.then(function(response) {
return response.json();
})
.then(function(json) {
// Need to return some values from this.
});
return (
<div>
<h1>{this.state.jsonReturnedValue}</h1>
</div>
);
}
}
提前致谢!
最佳答案
您应该调用 this.setState
以更改 state
值
export default class IndexPage extends React.Component {
constructor() {
super();
this.state = {
jsonReturnedValue: null
}
}
componentDidMount() {
fetch('https://localhost:3000/api/aye')
.then(response => response.json())
.then(json => {
this.setState({ jsonReturnedValue: json });
});
}
render() {
return (
<div>
<h1>{ this.state.jsonReturnedValue }</h1>
</div>
);
}
}
关于javascript - 如何根据 API 数据设置初始 React 状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41223306/