Перенаправление не работает в Accounts.createUser () - PullRequest
0 голосов
/ 19 февраля 2019

В meteorJS я использовал response-router-dom.Я попытался перенаправить после создания учетной записи.Теперь учетная запись успешно создана, но перенаправление не работает.

Я также пытался установитьState добавить, когда учетная запись успешно создана.Это также не работает.

   handleSubmit(event) {
        event.preventDefault();
        Accounts.createUser(
            {
                username: this.state.mobile,
                password: "123"
            },
            function(err) {
                if (err) {
                    console.log("err", err);
                } else {
                    console.log("account created");
                    this.setState({
                        redirect: true
                    });
                    return <Redirect to="/" />;
                }
            }
        );
    }

Это сообщение отображается в консоли

Exception in delivering result of invoking 'createUser': TypeError: this.setState is not a function

Ответы [ 2 ]

0 голосов
/ 19 февраля 2019

вы потеряли контекст

  handleSubmit(event) {
    event.preventDefault();
    let that = this;
    Accounts.createUser(
        {
            username: this.state.mobile,
            password: "123"
        },
        function(err) {
            if (err) {
                console.log("err", err);
            } else {
                console.log("account created");
                that.setState({
                    redirect: true
                });
                return <Redirect to="/" />;
            }
        }
    );
}
0 голосов
/ 19 февраля 2019

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

Кроме того, оператор return внутри обратного вызова не делает то, что, по вашему мнению, делает, это значениепотерян, вы должны нажать новый маршрут, используя объект истории

handleSubmit(event) {
  event.preventDefault();
  Accounts.createUser(
  {
    username: this.state.mobile,
    password: "123"
  },
  err => { // here use the arrow function to bind to the current "this"
    if (err) {
      console.log("err", err);
    } else {
      console.log("account created");
      this.setState({
        redirect: true
      });
      hashHistory.push("/"); // push the next route
    }
  });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...