[英]React SSR: Prevent client side rendering of components which are rendered on the server
I'm new to React. 我是React的新手。 I'm building a site with react, react router4, react redux, etc., in which few components get rendered on the server (mostly fetching data using API calls and display them).
我正在构建一个具有反应,反应router4,反应还原等的站点,其中很少的组件在服务器上呈现(主要是使用API调用获取数据并显示它们)。 Now my question is if I render component on the server and send rendered HTML to the client, it again gets rendered on the client (makes an API call), which I need to prevent.
现在我的问题是,如果我在服务器上呈现组件并将呈现的HTML发送到客户端,它将再次在客户端上呈现(进行API调用),我需要阻止它。
I don't want to render component again if it's already rendered on the server. 如果组件已经在服务器上呈现,我不想再次渲染组件。 How can I achieve this?
我怎样才能做到这一点?
Thanks 谢谢
Satish 萨蒂什
I have a similar problem. 我有一个类似的问题。 I have a large table (5000 rows) rendered on the server.
我在服务器上呈现了一个大表(5000行)。 i don't want to send the data to the client twice (in HTML and JSON form) I came up with this solution/hack.
我不想将数据发送到客户端两次(以HTML和JSON格式)我想出了这个解决方案/ hack。
Before rendering the table rows, the component first checks the DOM to see if a component exists with the same id (which if pre-rendered server-side will exist), if it does then it extracts the HTML and uses that directly via dangerouslySetInnerHTML
. 在呈现表行之前,组件首先检查DOM以查看组件是否存在具有相同的id(如果预先呈现的服务器端将存在),如果存在,则它将提取HTML并直接通过
dangerouslySetInnerHTML
使用它。
renderTable() {
debug('render table');
const id = 'table-body';
const html = this.getExistingHtml(id);
if (html) {
return <tbody id={ id } dangerouslySetInnerHTML={{ __html: html }} />;
}
return <tbody id={ id }>{ this.renderItems() }</tbody>;
}
getExistingHtml(id) {
if (typeof document === 'undefined') return;
const node = document.getElementById(id);
return node && node.innerHTML;
}
renderItems() {
debug('render items');
return this.props.items.map(({ name, url }) => {
return (
<tr>
<td>
<a href={ url }>
<div>{ name }</div>
</a>
</td>
</tr>
);
});
}
shouldComponentUpdate() {
return false;
}
I've also coupled this with shouldComponentUpdate
to prevent any renders after the initial mount. 我还将它与
shouldComponentUpdate
相结合,以防止在初始安装后进行任何渲染。
You may use hydrate from 'react-dom' 你可以使用'react-dom'中的水合物
https://reactjs.org/docs/react-dom.html#hydrate https://reactjs.org/docs/react-dom.html#hydrate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.