我的应用程序中有一个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 />
:
Login
代替我在上面的代码中使用的链接this.props.history.push("/Login")
window.history.replaceState("http://localhost:3000/#/Login")
<Link to="http://localhost:3000/#/Login" />
window.location.reload()
我不确定我还能做些什么。另外,因为我没有在我的axios.post
函数中将值作为查询字符串发送,所以我不明白为什么它们首先被添加到查询字符串中。
为什么会发生这种情况?如何防止将值添加到查询字符串?
答案 0 :(得分: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);
});
}