How can I pass data from express server to react views?

前端 未结 1 1442
感情败类
感情败类 2021-02-03 12:28

I have a simple express server with a connection to a orientdb database. I need to pass information from express to react views. For example, in express I have:

         


        
相关标签:
1条回答
  • 2021-02-03 13:08

    I think your best option is to indeed make some kind of network request from the client. If you aim to keep the app simple and do not want a State Management library (e.g. Redux), you could do something like

    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 there should be a JSON representation of the posts collection.

    Also note the render method and accessing the posts.

    For more on Fetch API see MDN (please also note that you will need a polyfill for older browsers for it).

    EDIT: For socket.io I'd store the instance of it somewhere and pass it as a prop to the component. Then you can do something like

    class IndexPage extends React.Component {
      ...
      componentDidMount() {
        this.props.socket.on('postReceived', this.handleNewPost);
      }
      handleNewPost = (post) => {
        this.setState({
          posts: [
            ...this.state.posts,
            post,
          ],
        });
      }
      ...
    }
    

    The server-side part is similar, see for example Socket.io Chat example.

    0 讨论(0)
提交回复
热议问题