【问题标题】:How can I pass data from express server to react views?如何从快速服务器传递数据以响应视图?
【发布时间】:2017-02-25 13:40:06
【问题描述】:

我有一个连接到 orientdb 数据库的简单快速服务器。 我需要从 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 中,我可以使用一些模板引擎,例如把手或 hogan。这个模板引擎可以帮助这个主题吗?

谢谢!!!

【问题讨论】:

  • 服务器端没有react,只能在前端使用

标签: node.js express reactjs socket.io


【解决方案1】:

我认为您最好的选择是确实从客户端发出某种网络请求。如果您的目标是保持应用程序简单并且不想要状态管理库(例如 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 中应该有一个 JSON 表示的帖子集合。

还要注意render 方法和访问posts

有关 Fetch API 的更多信息,请参阅 MDN(另请注意,您需要一个适用于旧版浏览器的 polyfill)。

编辑: 对于 socket.io,我会将它的实例存储在某处,并将其作为道具传递给组件。然后你可以做类似的事情

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

【讨论】:

  • 谢谢!如果我需要实时执行此操作,socket.io 中有一些类似 fetch 的功能吗?或者是一种完全不同的实时方式?服务器呢,是一样的
  • 服务器呢,我实时取数据是一样的,还是有很多变化?
  • 我在实时网络方面没有太多经验,但我认为 React 并不重要。您需要做的就是在新数据到达时调用setState(socket.io 会有一些回调)。服务器端将使用 socket.io 将 JSON 推送到客户端。最好找一些教程,我相信有很多。
猜你喜欢
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-05
  • 2023-03-08
  • 2018-08-01
  • 2020-08-30
相关资源
最近更新 更多