JCh*_*hao 7 javascript flash-message reactjs
我想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>
)}
Run Code Online (Sandbox Code Playgroud)
对于我的有状态组件,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);
})
Run Code Online (Sandbox Code Playgroud)
};
而我的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
Run Code Online (Sandbox Code Playgroud)
现在我的问题是每次点击提交,无论成功与否,它都会重新加载页面。因此,我认为我的状态已重新加载并且错误消失了。如果我添加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);
})
}
Run Code Online (Sandbox Code Playgroud)
目前尚不清楚为什么在成功调用后需要刷新整个页面并引导反应应用程序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);
})
}
Run Code Online (Sandbox Code Playgroud)
我希望这能给你一些想法。
归档时间: |
|
查看次数: |
460 次 |
最近记录: |