在react中显示Flash消息



我的任务是在单击提交按钮时显示flash消息("成功创建"(。[点击提交按钮,数据将存储在服务器中]我已经运行了这个命令npm I react flash message。

<form onSubmit={this.handleSubmit}>
<input type="submit" value="Submit" />
</form>

handleSubmit函数:

handleSubmit(event) {
fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: this.state.name,
description: this.state.description
})
}).then(res => {
return res.json()
})
.then(data => console.log(data))
.then(() => {
window.location.reload(false)
/* return (
<div>
<FlashMessage duration={5000}>
<strong>I will disapper in 5 seconds!</strong>
</FlashMessage>
</div>
) */
})
/* window.flash('record has been created successfully!', 'success') */
.catch(error => console.log('ERROR from create component'))
}
}

我已经评论了代码,我已经尝试显示闪光消息。但它不起作用。请有人帮我显示闪屏信息。

根据react flash消息页面,您应该在渲染中包含FlashMessage。因此,当你想显示FlashMessage 时,你可能需要有一个标志变量设置为true

示例:在渲染中:

<form onSubmit={this.handleSubmit}>
<input type="submit" value="Submit" />
{ this.state.showMessage &&  
<div>
<FlashMessage duration={5000}>
<strong>I will disappear in 5 seconds!</strong>
</FlashMessage>
</div>
}

</form>

handleSubmit函数:

handleSubmit(event) {
this.setState({ showMessage: false });
fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: this.state.name,
description: this.state.description
})
}).then(res => {
return res.json()
})
.then(data => console.log(data))
.then(() => {
this.setState({ showMessage: true });
})
/* window.flash('record has been created successfully!', 'success') */
.catch(error => console.log('ERROR from create component'))
}
}

主要功能,如果你使用类:

constructor(props) {
super(props);
this.state = {
showMessage: false
};
}

https://www.npmjs.com/package/react-flash-message

简单易用。。无论何时使用onSubmit,都不要忘记使用event.prventDefault((..

尝试只使用一个然后阻止。

现在维护一个状态变量,以设置结果的状态。获取结果后,将结果状态设置为true。

渲染你的FlashMessage组件,当它是真的。

https://codesandbox.io/s/lucid-taussig-9x0o3

最新更新