小编典典

如何传递来自快递服务器的数据以响应视图?

reactjs

我有一个简单的快递服务器,可以连接到orientdb数据库。我需要传递来自Express的信息以做出回应。例如,在快递中,我有:

router.get('/', function(req, res, next) {
  Vertex.getFromClass('Post').then(
    function (posts) {
      res.render('index', { title: 'express' });
    }
  );
});

因此,在此示例中,我需要在我的反应索引组件中包含posts用于设置组件状态的变量。(我仅在前端使用反应,而不在服务器端使用)

class IndexPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    };
  }

  render() {
    return (
      <div>
        <Posts posts={posts} />
      </div>
    );
  }
}

如何获得Express的回应?

我发现也许我可以通过react发出ajax请求,但是我认为那不是最好的方法。

如果我需要实时获取帖子,例如使用socket.io,有什么区别?

PD:明确地说,我可以使用一些模板引擎,例如把手或hogan。此模板引擎可以帮助解决此主题吗?

谢谢!!!


阅读 232

收藏
2020-07-22

共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中应该有posts集合的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示例

2020-07-22