gpt4 book ai didi

javascript - 从 url 中删除查询字符串 - HashRouter

转载 作者:行者123 更新时间:2023-12-03 02:21:35 25 4
gpt4 key购买 nike

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

到目前为止,这些表单都有效。注册后,用户应该被“重定向”到登录表单,以便他可以登录。但这通常是有效的,但是,由于某种原因,表单中输入的值(例如姓名、电子邮件、密码、密码确认、 ...)被添加到查询字符串中,然后该字符串看起来像这样: 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 中将值作为查询字符串发送函数,我不明白为什么它们首先被添加到查询字符串中。

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

最佳答案

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

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);
});
}

关于javascript - 从 url 中删除查询字符串 - HashRouter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49134307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com