我有一个休息 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>
);
}
}
提前致谢!
原文由 Zeokav 发布,翻译遵循 CC BY-SA 4.0 许可协议
您应该调用
this.setState
以更改state
值