【问题标题】:Redirect is not working in the Accounts.createUser()重定向在 Accounts.createUser() 中不起作用
【发布时间】:2019-07-12 23:34:31
【问题描述】:

我在meteorJS 中使用了react-router-dom。我在创建帐户后尝试重定向。现在帐户已成功创建,但重定向不起作用。

我也尝试在成功创建帐户时添加 setState。它也不起作用。

   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

【问题讨论】:

    标签: reactjs meteor react-router react-router-dom


    【解决方案1】:

    你失去了上下文

      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="/" />;
                }
            }
        );
    }
    

    【讨论】:

      【解决方案2】:

      您需要将回调绑定到您当前的上下文,您可以使用箭头函数来完成。

      此外,回调中的 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
          }
        });
      }
      

      【讨论】:

        猜你喜欢
        • 2013-05-25
        • 2011-09-08
        • 1970-01-01
        • 1970-01-01
        • 2017-10-08
        • 1970-01-01
        • 1970-01-01
        • 2011-08-02
        相关资源
        最近更新 更多