Как отобразить реагирующее уведомление после перенаправления на другую страницу? - PullRequest
0 голосов
/ 18 января 2019

У меня есть страница регистрации, разработанная с помощью 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 голосов
/ 18 января 2019

Вам не нужно связывать это, вы должны использовать функции стрелок

.then(response => {
    try{
      console.log(response);
      console.log('yes');
      history.push('/login');
      this.addNotification(response.data.message);
    } catch(error) {
      console.log('no');
    }
});
0 голосов
/ 18 января 2019
.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));
...