从url中移除查询字符串 - HashRouter

问题描述 投票:0回答:1

我的应用程序中有一个LoginContainer组件,它包含两个视图,一个登录表单和一个注册表单。因此,基本上这两个组件位于同一页面上,但是,根据用户单击的按钮,只会呈现其中一个按钮。

表格到目前为止有效。注册后,用户应该被“重定向”到登录表单,这样他就可以登录。但这通常有效,但由于某种原因,在表单中输入的值(例如姓名,电子邮件,密码,密码确认, ...)被添加到查询字符串,然后字符串看起来像这样:localhost:3000"?password=xyz&name=zyx'/Login

我尝试了很多东西(见下文),但我似乎无法想出办法来避免这种情况。

这就是我的路由器的样子:

<HashRouter basename="/">
    <div className="module">
    <PrivateRoute
        exact
        path={'/private'}
        component={privatecomponent}
      />
      <Route
        path="/Login"
        component={Login}
      />
    </div>
  </HashRouter>

这是我的注册页面:

 submitHandler = () => {

    var formdata = {
        "email" : this.state.email,
        "password" : this.state.password,
        "passwordConf" : this.state.password2,
        "firstName" : this.state.firstName,
    }
    axios.post('/adduser', formdata)
        .then(function (response) {
                this.setState({signup : true});
        })
        .catch(function (error) {
            console.log(error);
        });
  }

  render() {

const bodyBlock = 
    <div className="signup">

      <form>

        //here's a bunch of input fields which I left out

          <div>
            <Button
              onClick={this.submitHandler}
            >
              Sign Up
            </Button>
          </div>
      </form>
    </div>

   return (
      <div className="signup">
            {this.state.signup ? //
                <Redirect to="http://localhost:3000/#/Login" />
                : bodyBlock
            }
      </div>
    )
   }

我知道这是很多代码。我不确定你们需要哪些部件。如果您发现某个部分无关紧要,请告诉我,我会缩短问题。

无论如何,我尝试的,而不是<Redirect />是:

  1. 只需使用Login而不是我在上面的代码中使用的链接
  2. 使用this.props.history.push("/Login")
  3. window.history.replaceState("http://localhost:3000/#/Login")
  4. <Link to="http://localhost:3000/#/Login" />
  5. window.location.reload()

我不确定我还能做些什么。另外,因为我没有在axios.post函数中将值作为查询字符串发送,所以我不明白为什么它们首先被添加到查询字符串中。

为什么会发生这种情况,如何防止将值添加到查询字符串中?

javascript reactjs axios
1个回答
1
投票

你需要在你的e.preventDefault()形式中使用submitHandler。默认情况下,表单提交将刷新页面并将表单值添加为查询参数。

submitHandler = e => {

    e.preventDefault();

    var formdata = {
        "email" : this.state.email,
        "password" : this.state.password,
        "passwordConf" : this.state.password2,
        "firstName" : this.state.firstName,
    }
    axios.post('/adduser', formdata)
        .then(function (response) {
                this.setState({signup : true});
        })
        .catch(function (error) {
            console.log(error);
        });
  }
© www.soinside.com 2019 - 2024. All rights reserved.