我想用fetch()
通过在我的阵营通用(含Next.js)应用REST服务调用来接收数据,然后将结果呈现到JSX是这样的:如何呈现从React Universal中的REST服务接收到的数据? (Next.js)
class VideoPage extends Component {
componentWillMount() {
console.log('componentWillMount');
fetch(path, {
method: 'get',
})
.then(response =>
response.json().then(data => {
this.setState({
video: data,
});
console.log('received');
})
);
}
render() {
console.log('render');
console.log(this.state);
if (this.state && this.state.video) {
return (
<div>
{this.state.video.title}
</div>
);
}
}
}
export default VideoPage;
不幸的是,输出是这样的:
componentWillMount
render
null
received
这有一定道理,因为获取呼叫和异步调用REST服务之前render()
结束已完成。
在客户端应用程序中,这是没有问题的,因为状态更改会调用render()
,然后更新视图,但是在通用应用程序中,特别是在客户端关闭JavaScript的情况下,这是不可能的。
我该如何解决这个问题?
有没有办法同步调用服务器或延迟render()
?