重定向到另一个页面后如何显示反应通知? [英] How to display a react-notification after redirect to another page?

查看:64
本文介绍了重定向到另一个页面后如何显示反应通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Signup page developed with ReactJS and I want after the click of submit button, it redirects me to login page, after that it display a react-notification which message is 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} />

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

When I run it, it redirects me to the login page and the notification not working and I get no in the console of catch.

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

How can I fix that or have you a suggestion to use another system for notifications ?

推荐答案

你不需要绑定这个,你应该使用箭头函数

You don't need to bind this, you should use arrow functions

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

这篇关于重定向到另一个页面后如何显示反应通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆