San*_*uri 7 node.js express socket.io reactjs
我有一个简单的快速服务器与orientdb数据库的连接.我需要将信息从快递传递到反应视图.例如,在表达中我有:
router.get('/', function(req, res, next) {
Vertex.getFromClass('Post').then(
function (posts) {
res.render('index', { title: 'express' });
}
);
});
Run Code Online (Sandbox Code Playgroud)
因此,在这个例子中,我需要在我的react索引组件posts中设置变量来设置组件的状态.(我使用的只是在前端,而不是服务器端)
class IndexPage extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
render() {
return (
<div>
<Posts posts={posts} />
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
如何从快递中获得回复的帖子?
我发现也许我可以从反应中做一个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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
在你的response应该有post集合的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,
],
});
}
...
}
Run Code Online (Sandbox Code Playgroud)
服务器端部分类似,请参阅Socket.io Chat示例.
| 归档时间: |
|
| 查看次数: |
9260 次 |
| 最近记录: |