我正在使用ReactJS + Router渲染我的网站服务器端 ,我的许多组件都会进行REST调用以生成内容.此内容不会作为HTML服务器端发送,因为它是异步调用.
一个看起来像这样的组件:
import React from 'react'
import ReactDOM from 'react-dom'
// Imports omitted
export default class MyPage extends React.Component {
constructor() {
super();
this.state = {items: []};
fetch("http://mywebservice.com/items").then((response) => {
response.json().then((json) => {
this.setState({items: json.items})
}).catch((error) => {});
});
}
render() {
if (this.state.items && this.state.items.length > 0) {
var rows = [];
// Go through the items and add the element
this.state.items.forEach((item, i) => {
rows.push(<div key={item.id}></div>);
});
return <div>
<table>
{rows}
</table>
</div>;
} …
Run Code Online (Sandbox Code Playgroud)