重定向到另一个页面后如何显示反应通知?

时间:2019-01-18 10:47:52

标签: javascript reactjs notifications

我有一个用ReactJS开发的注册页面,我想在单击“提交”按钮后将其重定向到登录页面,然后显示一个反应通知,该消息是response.data.message

我使用了react-notifications-component

import ReactNotification from "react-notifications-component";
export default class Signup extends Component {
  constructor(props) {
    super(props);
    this.addNotification = this.addNotification.bind(this);
    this.notificationDOMRef = React.createRef();
  }
 addNotification(message) {
    this.notificationDOMRef.current.addNotification( {
      title: "Awesomeness",
      message:{message},
      type: "success",
      insert: "top",
      container: "top-right",
      animationIn: ["animated", "fadeIn"],
      animationOut: ["animated", "fadeOut"],
      dismiss: { duration: 2000 },
      dismissable: { click: true }
    });

  }

 handleSubmit =  event => {
    event.preventDefault();
    const users = {
      name:this.state.name,
      email:this.state.email,
    }
    console.log(users)
   const { history } = this.props
   axios({
    method: 'post',
    url: 'http://172.16.234.24:8000/api/register',
    data: users,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    }
    })
    .then(function (response) {

         try{
      console.log(response);
      console.log('yes');
      history.push('/login');
      this.addNotification(response.data.message);
             }
        catch{
      console.log('no');
            }

    })
    .catch(function (response) {
        console.log(response);
    });

  }
<Button type="submit" onClick={this.handleSubmit}>Register </Button>
          <ReactNotification ref={this.notificationDOMRef} />

运行它时,它会将我重定向到登录页面,并且通知不起作用,并且在no的控制台中显示了catch

我该如何解决此问题,或者有建议您使用其他系统进行通知?

2 个答案:

答案 0 :(得分:2)

您不需要绑定它,应该使用箭头功能

.then(response => {
    try{
      console.log(response);
      console.log('yes');
      history.push('/login');
      this.addNotification(response.data.message);
    } catch(error) {
      console.log('no');
    }
});

答案 1 :(得分:1)

.then(function (response) {
    try{
      console.log(response);
      console.log('yes');
      history.push('/login');
      this.addNotification(response.data.message);
    } catch(error) {
      console.log('no');
    }
}.bind(this));