在反应中显示 Flash 消息

use*_*964 3 flash-message reactjs

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

<form onSubmit={this.handleSubmit}>
   <input type="submit" value="Submit" />
 </form>
Run Code Online (Sandbox Code Playgroud)

处理提交函数:

  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'))
      }
     }
Run Code Online (Sandbox Code Playgroud)

我已经评论了我试图显示 Flash 消息的代码。但它不起作用。请有人帮我显示 Flash 消息。

小智 6

根据 react-flash-message page ,您应该在渲染中包含 FlashMessage。因此,当您想显示 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>
Run Code Online (Sandbox Code Playgroud)

处理提交功能:

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'))
      }
}
Run Code Online (Sandbox Code Playgroud)

如果您正在使用类,则主要功能:

 constructor(props) {
    super(props);
    this.state = {
      showMessage: false
    };
  }
Run Code Online (Sandbox Code Playgroud)

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