【发布时间】:2020-04-20 16:33:10
【问题描述】:
如果后端有任何更改作为 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
})
}
}
}
谁能帮我解决这个问题?
【问题讨论】:
-
TLDR,“shouldComponentUpdate”可以用吗?
-
低级解决方案:您可以安排一个作业(或 setInterval)每隔一定时间(例如每 5 分钟)获取一次请求,并更新您的请求列表的状态。和更高的解决方案,我认为你应该研究长轮询技术。
标签: javascript reactjs