【发布时间】:2020-09-16 16:30:42
【问题描述】:
我正在做我的第一个 React 项目。
提交表单时我想做两件事:
- 将表单数据发布到后端
- 重定向到感谢页面
我可以使用 handleSubmit(下面的代码)将表单数据发布到后端,但正在寻找一种方法来合并重定向。
handleSubmit = (event) => {
event.preventDefault();
try {
await fetch('http://localhost:5000/results', {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state)
}).then(function(response){
console.log(response)
return response.json();
});
}
catch (error){
console.log(error);
}
}
这就是在表单上调用 handleSubmit 的方式
<form onSubmit={this.handleSubmit}
action="http://localhost:5000/results" method="post"
>
这就是我想作为 handleSubmit 的一部分合并的内容
<Redirect to="/thank-you/" />
编辑:withRouter/this.props.history.push
import { withRouter } from 'react-router-dom';
class Form extends React.Component {
handleSubmit = async event => {
event.preventDefault();
try {
await fetch('http://localhost:5000/results', {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state)
}).then(function(response){
console.log(response)
return response.json();
this.props.history.push("/thankyou");
});
}
catch (error){
console.log(error);
}
}
}
export default withRouter(Form);
编辑2:重写handleSubmit,将BrowserRouter添加到App
//form.component.jsx
class Form extends React.Component {
handleSubmit = (event) => {
event.preventDefault();
fetch('http://localhost:5000/results', {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state)
}).then((response) => response.json())
.then((json) => {
console.log(json)
this.props.history.push("/thank-you");
})
.catch((error) => console.log(error.message));
};
export default Form;
//app.js
import { BrowserRouter, Route } from 'react-router-dom';
class App extends React.Component {
return (
<BrowserRouter>
<Route exact path='/form' component= {Form}/>
<Route exact path='/thank-you' component={ThankYou}/>
</BrowserRouter>
);
}
export default App;
【问题讨论】:
-
在您的
.then()中,设置一个状态变量,例如this.setState( { redirect: true } )(使用箭头函数进行回调,这样您就不会丢失正确的this)。现在您可以简单地将{ this.state.redirect && <Redirect to="/thank-you/" />}添加到您的组件中。 (另请注意,您可以使用event.target.getAttribute('action')从表单中获取url,或者从<form>中删除action属性)
标签: javascript reactjs