首页 > 解决方案 > reactjs中如何在不刷新页面的情况下更新状态

问题描述

如果后端有任何更改作为 Facebook 中的通知,我想更新我的仪表板。

我有两页:

如果有新的请求消息,用户需要刷新用户配置文件才能看到新消息。我希望在不刷新页面的情况下显示新消息。这是我的代码:

在消息页面中

state = {

    team: {
      message: 'Hi! I would like to join in your team! Please accept my request',
      invitation_message: 'Hi! I would like to invite you to join in my team.',
      email: '',
    },

  }
  // Invite user to a team
  handleInvite = event => {
    event.preventDefault();
    const userObject = JSON.parse(localStorage.getItem('user'));
    const jwt = userObject.jwt;
    const config = {
      headers: { 'Authorization': `bearer ${jwt}` },
    };     
    api
      .post('/teammembers', {
        team: this.state.teaminfo,
        profile: responseData.data[0],
        status: "invited",
        message: this.state.team.invitation_message,
      }, config)
      .then(response => {
        this.setState({
          success_message: true,
        })
        console.log('Success', response);
      })
      .catch(err => {
        console.log('An error occurred:', err);
      });

  }


在用户个人资料页面中

export class UserProfile extends React.Component {
import socketIOClient from "socket.io-client";

state = {

    invited_teams:[],
    endpoint: "myurl"

  }
 componentDidMount() {
 const { endpoint } = this.state;
    //Very simply connect to the socket
    const socket = socketIOClient(endpoint);
    socket.on('request', (data) => {
      this.setState({ state: data.requests });
    });
    if (localStorage.getItem('userData')) {
      const userObject = JSON.parse(localStorage.getItem('user'));
      api
        .get(`/profiles/?user=${userObject.user.id}`)
        .then(responseData => {
          this.setState({
            invited_teams: responseData.data
          })
        }
    }      
}

谁能帮我解决这个问题?

标签: javascriptreactjs

解决方案


使用 socket.IO 库。您可以在新请求上设置监听器,然后更新状态。

socket.on('request' , (data) => {
  this.setState({state: data.requests});
});

推荐阅读