如何将数据从 Express 服务器传递到反应视图?

2023-11-22

我有一个简单的 Express 服务器,连接到 orientdb 数据库。 我需要将信息从 Express 传递到 React 视图。 例如,在快递中我有:

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

所以,在这个例子中,我需要在我的反应索引组件中包含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 中,我可以使用一些模板引擎,如车把或霍根。这个模板引擎可以帮助解决这个主题吗?

谢谢!!!


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

In your response应该有 posts 集合的 JSON 表示形式。

另请注意render方法并访问posts.

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

EDIT:对于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 聊天示例.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将数据从 Express 服务器传递到反应视图? 的相关文章

随机推荐