[英]How to render data received from a REST service in React Universal? (Next.js)
I want to receive data via a REST service call in my React Universal (with Next.js) app using fetch()
and then render the result into JSX like this: 我希望通过使用
fetch()
在我的React Universal(使用Next.js)应用程序中通过REST服务调用接收数据,然后将结果呈现为JSX,如下所示:
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;
Unfortunately, the output is this: 不幸的是,输出是这样的:
componentWillMount
render
null
received
Which does make sense because the call to fetch is asynchronously and render()
finishes before the call to the REST service has finished. 这有意义,因为对fetch的调用是异步的,
render()
在调用REST服务之前完成。
In a client-side app this would be no problem because a change of state would call render()
which then updates the view, but in a universal app, especially with JavaScript turned off on the client, this is not possible. 在客户端应用程序中,这没有问题,因为更改状态会调用
render()
然后更新视图,但在通用应用程序中,尤其是在客户端关闭JavaScript时,这是不可能的。
How can I solve this? 我怎么解决这个问题?
Is there a way to call the server synchronously or delay render()
? 有没有办法同步调用服务器或延迟
render()
?
In order to get it working, I had to do 3 things: 为了让它工作,我必须做三件事:
componentWillMount
with getInitialProps() method componentWillMount
fetch
with await
and return the data fetch
与await
结合并返回数据 this.props
instead of this.state
this.props
而不是this.state
Code looks like this now: 代码现在看起来像这样:
static async getInitialProps({ req }) {
const path = 'http://path/to/my/service';
const res = await fetch(path);
const json = await res.json();
return { video: json };
}
Then, in render()
I can access the data via this.props.video
, for example: 然后,在
render()
我可以通过this.props.video
访问数据,例如:
render() {
return (
<div>{this.props.video.title}</div>
);
}
You can add static async getInitialProps () {}
to load data into props before the page component gets rendered. 您可以添加
static async getInitialProps () {}
以在呈现页面组件之前将数据加载到props中。
More info here: https://github.com/zeit/next.js/blob/master/readme.md#fetching-data-and-component-lifecycle 更多信息: https : //github.com/zeit/next.js/blob/master/readme.md#fetching-data-and-component-lifecycle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.