如何传递来自快递服务器的数据以响应视图? [英] How can I pass data from express server to react views?
问题描述
我有一个简单的快递服务器,它与orientdb数据库建立了连接. 我需要传递来自Express的信息以回应观点. 例如,在快递中,我有:
I have a simple express server with a connection to a orientdb database. I need to pass information from express to react views. For example, in express I have:
router.get('/', function(req, res, next) {
Vertex.getFromClass('Post').then(
function (posts) {
res.render('index', { title: 'express' });
}
);
});
因此,在此示例中,我需要在我的反应索引组件中包含posts
变量以设置组件的状态. (我仅在前端使用反应,而不是服务器端)
So, in this example, I need to have in my react index component, the posts
variable to set the state of the componenent. (I'm using react only in the frontend, not server-side)
class IndexPage extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
render() {
return (
<div>
<Posts posts={posts} />
</div>
);
}
}
我该如何从Express中获得回复?
How can I get the posts in react from express?
我发现也许我可以通过react发出ajax请求,但是我认为那不是最好的方法.
I found that maybe I can do an ajax request from react, but I think that that isn't the best way.
如果我需要实时获取帖子,例如使用socket.io,有什么区别?
If I need to get that posts in a real time way, using socket.io for example, what are the differences?
PD:在快速表达中,我可以使用一些模板引擎,例如把手或霍根(hogan).此模板引擎可以帮助您解决此主题吗?
PD: In express I have the possibility to use some template engine like handlebars or hogan. Can this template engines help in this topic?
谢谢!
推荐答案
我认为您最好的选择是确实从客户端发出某种网络请求.如果您希望保持应用程序的简单性,并且不想使用状态管理库(例如Redux),则可以执行以下操作
I think your best option is to indeed make some kind of network request from the client. If you aim to keep the app simple and do not want a State Management library (e.g. Redux), you could do something like
class IndexPage extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
componentDidMount() {
fetch('/') // or whatever URL you want
.then((response) => response.json())
.then((posts) => this.setState({
posts: posts,
});
}
render() {
return (
<div>
<Posts posts={this.state.posts} />
</div>
);
}
}
在您的response
中,应该有一个posts集合的JSON表示形式.
In your response
there should be a JSON representation of the posts collection.
还要注意render
方法并访问posts
.
有关Fetch API的更多信息,请参见 MDN (另请注意,您将需要为旧版浏览器使用一个polyfill.
For more on Fetch API see MDN (please also note that you will need a polyfill for older browsers for it).
对于socket.io,我将其实例存储在某个地方,并将其作为道具传递给组件.然后您可以做类似的事情
For socket.io I'd store the instance of it somewhere and pass it as a prop to the component. Then you can do something like
class IndexPage extends React.Component {
...
componentDidMount() {
this.props.socket.on('postReceived', this.handleNewPost);
}
handleNewPost = (post) => {
this.setState({
posts: [
...this.state.posts,
post,
],
});
}
...
}
服务器端部分与此类似,例如参见 Socket.io聊天示例.
The server-side part is similar, see for example Socket.io Chat example.
这篇关于如何传递来自快递服务器的数据以响应视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!