javascript - 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
})
}
}
}
谁能帮我解决这个问题?
解决方案
使用 socket.IO 库。您可以在新请求上设置监听器,然后更新状态。
socket.on('request' , (data) => {
this.setState({state: data.requests});
});
推荐阅读
- azure-devops-migration-tools - 无法使用 azure-devops-migration-tools 连接到目标集合。获取“您无权访问 xxxxx”
- vba - 打印具有多个参数的报告时如何使用“AND”?
- android - 如何查看蓝牙连接日志
- javascript - 保存页面后删除突出显示
- python - Pandas 中 Groupby 函数的问题
- python - 在 TensorFlow 教程中使用自定义数据集
- java - 如何使用 fromGson 映射数组等中的对象?
- kubernetes - 如何将动态数据传递给 helm 子图
- r - 有没有办法让 R 中的函数输出成为 R 降价块?
- javascript - 倒计时服务器端最佳实践