如何从快速服务器传递数据以反应视图?

时间:2016-10-16 14:57:01

标签: node.js express reactjs socket.io

我有一个简单的快速服务器,它连接到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。这个模板引擎可以帮助解决这个问题吗?

感谢!!!

1 个答案:

答案 0 :(得分:7)

我认为您最好的选择是确实从客户端发出某种网络请求。如果您的目标是保持应用程序简单并且不需要状态管理库(例如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我将它的实例存储在某处并将其作为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

相关问题