在反应警报获取中显示

时间:2019-10-16 11:54:12

标签: reactjs alert

我想在使用访存更新后显示成功或失败的警报。我可以使用按钮显示一条消息,但是在提取操作中没有显示警报。

如何在提取中显示提醒

显示在反应警报获取中

我正在使用react-alert组件。 https://www.npmjs.com/package/react-alert


      async handleSubmitUpdate() {

        await fetch(`${this.domain}/api/debt/update/`, {
          method: "PUT",
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            user: this.props..id, 
          })
        })
          .then(response => {
            return response.json();
          })
          .then(json => {
            this.componentDidMount();

                return (<AlertMessageBox type={"success"} data={"Update succesfully"} />)
          })
          .catch(err => console.log(err));
      }

AlertMessageBox.js


    import React from 'react';
    import { useAlert } from 'react-alert';


    const AlertMessageBox = ({ type, data }) => {
        const alert = useAlert();

        console.log(data);

        const showAlert = () =>  {
            switch (type) {
                case 'error':
                    alert.error(<div style={{color: 'red'}}> data </div>);
                    return;
                case 'show':
                    alert.show(<div style={{color: 'white'}}> data </div>);
                    return;
                case 'info':
                    alert.success(<div style={{color: 'green'}}> data </div>);
                    return;
                default:
                    return;
            }
        };
        return <div> { showAlert() }  Deneme</div>;
    };

    export default AlertMessageBox;

1 个答案:

答案 0 :(得分:0)

您应该为此设置一个状态变量。

state = {
   showSuccessAlert: false,
   showFailAlert: false
}

然后您可以在成功/失败时设置状态变量,

await fetch(`${this.domain}/api/debt/update/`, {
  method: "PUT",
  headers: {
      Authorization: `Bearer ${localStorage.getItem("token")}`,
      "Content-Type": "application/json"
  },
  body: JSON.stringify({
      user: this.props..id,
  })
})
.then(response => {
  return response.json();
})
.then(json => {
  //this.componentDidMount();    //I don't think you can call this

  //Change the state here which will show your Alert
  this.setState({
    showSuccessAlert: true
  })
})
.catch(err => {
  console.log(err);

  //Change the state here which will show your Alert
  this.setState({
    showFailAlert: true
  })
);

在渲染方法中,您应该具有条件的警报

render(){
   return(
     <div>
        { this.state.showSuccessAlert && <AlertMessageBox type={"success"} data={"Update succesfully"} /> }

        { this.state.showFailAlert && <AlertMessageBox type={"error"} data={"Data update failed"} /> }

        ....
     </div>
   )
}