Reactjs 在react中显示Flash消息
我的任务是在单击提交按钮时显示flash消息(“成功创建”)。[单击提交按钮时,数据将存储在服务器中]我已运行此命令npm I react flash messageReactjs 在react中显示Flash消息,reactjs,flash-message,Reactjs,Flash Message,我的任务是在单击提交按钮时显示flash消息(“成功创建”)。[单击提交按钮时,数据将存储在服务器中]我已运行此命令npm I react flash message <form onSubmit={this.handleSubmit}> <input type="submit" value="Submit" /> </form> handleSubmit函数: handleSubmit(event) { fetch('url',
<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'))
}
}
handleSubmit(事件){
获取('url'{
方法:“POST”,
标题:{
“内容类型”:“应用程序/json”
},
正文:JSON.stringify({
名称:this.state.name,
description:this.state.description
})
})。然后(res=>{
return res.json()
})
.then(数据=>console.log(数据))
.然后(()=>{
window.location.reload(false)
/*返回(
我将在5秒内消失!
) */
})
/*flash('记录已成功创建!','success')*/
.catch(错误=>console.log('error from create component'))
}
}
我已经注释了我试图显示flash消息的代码。但它不起作用。请有人帮我显示flash消息。轻松。。
无论何时使用onSubmit,都不要忘记使用event.preventDefault()
然后尝试只使用一个块
现在维护一个状态变量,以设置结果的状态。获取结果后,将结果状态设置为true
渲染FlashMessage组件(如果为true)
根据react flash message页面,您应该在渲染中包含flash message。因此,当您想要显示FlashMessage时,可能需要将标志变量设置为true 例如: 在渲染中:
<form onSubmit={this.handleSubmit}>
<input type="submit" value="Submit" />
{ this.state.showMessage &&
<div>
<FlashMessage duration={5000}>
<strong>I will disapper in 5 seconds!</strong>
</FlashMessage>
</div>
}
</form>
如果您使用的是类,则主要函数:
constructor(props) {
super(props);
this.state = {
showMessage: false
};
}
感谢您的快速回复和建议。此代码帮助我显示flash消息。感谢您的回复。是的,这个代码显示闪光信息。非常感谢。
constructor(props) {
super(props);
this.state = {
showMessage: false
};
}