如果后端中的任何更改作为Facebook中的通知,我想更新我的仪表板。我有2页:1页用于用户发送请求消息,1页用于用户配置文件,用户可以在其中查看所有请求消息。如果有新的请求消息,则用户需要刷新用户的配置文件才能看到新消息。我希望显示新消息而不刷新页面。这是我的密码
在消息页面中
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
})
}
}
}
有人可以帮我解决这个问题吗?非常感谢高级:)
答案 0 :(得分:0)
使用socket.IO库。您可以在新请求上设置侦听器,然后更新状态。
socket.on('request' , (data) => {
this.setState({state: data.requests});
});