[英]React - redirect after complete form submission
I'm new to React
, sorry if this is too basic.我是
React
新手,如果这太基本了,对不起。
I'm trying to perform a redirect
to a page when a form is submitted.我正在尝试在提交表单时
redirect
到页面。 For that I'm using this.redirect.state
, since state changes re-renders the component.为此,我使用
this.redirect.state
,因为 state 更改会重新渲染组件。
Then I set state update as condition inside render()
for redirection.然后我将 state 更新设置为
render()
内的条件以进行重定向。
However, I'm being redirected as soon as I enter one single character at form -any change, and this is undesired.但是,只要我在表单中输入一个字符 - 任何更改,我就会被重定向,这是不希望的。
How do I redirect after complete form submission?完成表单提交后如何重定向?
Here's my code:这是我的代码:
class Seeds extends Component{
constructor (props) {
super(props);
this.state = {
formSeeds: {
arabica:'',
hybrid:'',
robusta:'',
my_bean:'',
},
redirect: false
};
handleSubmitMyBean(event) {
event.preventDefault();
//const formType = this.props.formType
const {userId} = this.props
var headers = {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
const data = {
my_bean: this.state.formSeeds.my_bean
};
const url = `${process.env.REACT_APP_WEB_SERVICE_URL}/handle_seeds/${userId}`;
axios.post(url, data, headers)
.then((res) => {
//this.clearSeedsForm()
console.log(data);
})
.catch((error) => { console.log(error);
});
};
handleSeedFormChange(event) {
console.log(event)
const obj = Object.assign({}, this.state.formSeeds);
obj[event.target.name] = event.target.value;
this.setState({ formSeeds: obj });
this.validateForm();
};
render(){
<div>
if(this.state.formSeeds.my_bean){
return (<Redirect to='/edit-coffee' />);
}
<form onSubmit={ (event) => this.handleSubmitMyBean(event) }>
<div className="field">
<input
name="my_bean"
className="input is-dark is-large"
type="text"
placeholder="Enter Bean"
value={this.state.formSeeds.my_bean}
onChange={this.handleMyBeanFormChange}
/>
</div>
<input
type="submit"
className="button is-dark is-small is-fullwidth"
value="Seed Bean"
//disabled={!this.state.valid}
/>
</form>
</div>
)
}
Your redirect depends on this.state.formSeeds.my_bean
which you update on change.您的重定向取决于您在更改时更新的
this.state.formSeeds.my_bean
。
Change your post callback to update the redirect
state:更改您的帖子回调以更新
redirect
state:
axios.post(url, data, headers)
.then((res) => {
console.log(data);
this.setState({ redirect: true }); // <---
})
.catch((error) => {
console.log(error);
});
And update your render method so it redirects on the right state change:并更新您的渲染方法,使其重定向到右侧 state 更改:
render() {
if(this.state.redirect) {
return (<Redirect to='edit-cofee' />);
} else {
return (
<div> ... </div>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.