我想使用 FlashMessage
显示错误(或成功)消息同时让我的页面在所需时间重新加载
我正在使用 FlashMessage
我的代码看起来像
render() {
return (
{this.state.error ? <FlashMessage duration={5000}><strong>{this.state.error.message}</strong></FlashMessage> : ''}
//Some table here presenting data
<Button variant="outline-info" type="submit" size="lg" block className="button-custom" onClick={this.handleSubmit.bind(this)}>
Submit
</Button>
)}
对于我的有状态组件,error
由加载handleSubmit(event) {
let data = {
name: this.state.name,
unit_price: this.state.unit_price,
length: this.state.length,
time: this.state.selectedDate,
instructor: this.state.instructor,
}
ApiService.postLesson(data)
.then(res => {
this.setState({
message: 'Success!'
});
})
.catch(error => {
this.setState({
message: error,
error: error,
});
console.log(error);
})
};和我的
ApiService.postLesson
是const instance = axios.create({
headers: {
"Content-Type": "application/json",
Authorization: 'Token ' + localStorage.getItem('token')
},
});
export default {
postLesson: data =>
instance({
'method': 'POST',
'url': BACKEND_LESSONS_URL,
'data': data
}),
// some other services
现在我的问题是每次点击提交,无论成功与否,都会重新加载页面。因此,我认为我的状态已重新加载并且错误消失了。如果我添加 event.preventDefault()
在 handleSubmit
,然后我可以看到该消息,但我在表格中的内容不会更新。有什么解决方案?
最佳答案
看来你是在正确的轨道上,event.preventDefault()
对于您要实现的目标,这确实是必要的。
因此,您可以通过调用 location.reload()
刷新成功页面:
handleSubmit(event) {
event.preventDefault();
let data = {
name: this.state.name,
unit_price: this.state.unit_price,
length: this.state.length,
time: this.state.selectedDate,
instructor: this.state.instructor,
}
ApiService.postLesson(data)
.then(res => {
this.setState({
message: 'Success!'
});
location.reload(); // refreshes the page
})
.catch(error => {
this.setState({
message: error,
error: error,
});
console.log(error);
})
}
不清楚为什么成功后需要刷新整个页面并引导react app postLesson()
来电。但是,对于您的情况,可能有更好的选择:handleSubmit(event) {
event.preventDefault();
let data = {
name: this.state.name,
unit_price: this.state.unit_price,
length: this.state.length,
time: this.state.selectedDate,
instructor: this.state.instructor,
}
ApiService.postLesson(data)
.then(res => {
this.setState({
message: 'Success!'
});
// 1. re-fetching list of items
// ApiService.getLessons().then((lessons) => {this.setState({lessons})})
// or 2. add newly posted lesson to the list
// this.setState({lessons: this.state.lessons.concat(data)})
})
.catch(error => {
this.setState({
message: error,
error: error,
});
console.log(error);
})
}
我希望这能给你一些想法。
关于javascript - react 闪存消息 : How to make the message show without refreshing the page but refresh on 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65062295/