gpt4 book ai didi

node.js - 用后端请求响应服务器端渲染

转载 作者:太空宇宙 更新时间:2023-11-04 02:11:23 28 4
gpt4 key购买 nike

我有一个通过 Express 进行服务器端渲染的 React 应用程序。我有简单的应用程序组件:

import React, { Component } from 'react';

export default class App extends Component {
constructor(props) {
super(props)

this.state = {
data: []
};

fetch('http://backend', {
mode: 'cors',
})
.then(res => res.json())
.then(data => this.state.data);
}

render() {
return (
<ul>
{this.state.data.map(item => (
<li key={item}>{item}</li>
))}
</ul>
);
}
};

问题(或更可能的特征)是 fetch 是异步工作的。因此浏览器获取的页面包含空数据。

有没有办法从服务器页面获取加载的数据?假设我想从服务器页面获取已加载的帖子或其他内容。

或者我有什么问题吗?

最佳答案

您没有正确设置状态。使用 setState() 设置新状态,因为如果不使用 setState() 方法就无法更新状态:https://facebook.github.io/react/docs/react-component.html#setstate

fetch('http://backend', {
mode: 'cors',
})
.then(res => res.json())
.then(data => this.setState({data: data}));

此外,您添加的代码不是使用 React 的服务器端渲染。您使用方法 ReactDOMServer.renderToString() 进行服务器端渲染:https://facebook.github.io/react/docs/react-dom-server.html#rendertostring

关于node.js - 用后端请求响应服务器端渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41936255/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com