我有一个连接到 orientdb 数据库的简单 express 服务器。 我需要从 express 传递信息以响应 View 。 例如,在 express 中我有:
router.get('/', function(req, res, next) {
Vertex.getFromClass('Post').then(
function (posts) {
res.render('index', { title: 'express' });
}
);
});
因此,在此示例中,我需要在我的 React 索引组件中使用 posts
变量来设置组件的状态。 (我只在前端使用 react ,而不是服务器端)
class IndexPage extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
render() {
return (
<div>
<Posts posts={posts} />
</div>
);
}
}
如何从 express 中获取 react 中的帖子?
我发现也许我可以通过 React 执行 ajax 请求,但我认为那不是最好的方法。
如果我需要实时获取帖子,例如使用 socket.io,有什么区别?
PD:在 express 中,我可以使用一些模板引擎,例如 handlebars 或 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>
);
}
}
在您的响应
中应该有帖子集合的 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 example .
关于node.js - 如何从 Express 服务器传递数据以响应 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40071686/