[英]How can I pass data from express server to react views?
我有一个简单的快速服务器与orientdb数据库的连接。 我需要将信息从快递传递到反应视图。 例如,在表达中我有:
router.get('/', function(req, res, next) {
Vertex.getFromClass('Post').then(
function (posts) {
res.render('index', { title: 'express' });
}
);
});
所以,在这个例子中,我需要在我的react索引组件中,使用posts
变量来设置组件的状态。 (我使用的只是在前端,而不是服务器端)
class IndexPage extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
render() {
return (
<div>
<Posts posts={posts} />
</div>
);
}
}
如何从快递中获得回复的帖子?
我发现也许我可以从反应中做一个ajax请求,但我认为这不是最好的方法。
如果我需要以实时方式获取帖子,例如使用socket.io,有什么区别?
PD:在表达中,我有可能使用一些模板引擎,如把手或hogan。 这个模板引擎可以帮助解决这个问题吗?
谢谢!!!
我认为你最好的选择是确实从客户端做出某种网络请求。 如果您的目标是保持应用程序简单并且不需要状态管理库(例如Redux),那么您可以执行类似的操作
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表示。
还要注意render
方法和访问posts
。
有关Fetch API的更多信息,请参阅MDN (另请注意,您需要为旧版浏览器使用polyfill)。
编辑:对于socket.io我将它的实例存储在某处并将其作为prop传递给组件。 然后你可以做类似的事情
class IndexPage extends React.Component {
...
componentDidMount() {
this.props.socket.on('postReceived', this.handleNewPost);
}
handleNewPost = (post) => {
this.setState({
posts: [
...this.state.posts,
post,
],
});
}
...
}
服务器端部分类似,请参阅Socket.io Chat示例 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.