Javascript React.js-在表单提交时,将数据发布到后端并重定向页面
我正在做我的第一个项目 提交表单时,我想做两件事:Javascript React.js-在表单提交时,将数据发布到后端并重定向页面,javascript,reactjs,Javascript,Reactjs,我正在做我的第一个项目 提交表单时,我想做两件事: 将表单数据发布到后端 重定向到感谢页面 我能够使用handleSubmit(下面的代码)将表单数据发布到后端,但正在寻找一种合并重定向的方法 handleSubmit = (event) => { event.preventDefault(); try { await fetch('http://localhost:5000/results', {
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"
>
编辑2:重写handleSubmit,将BrowserRouter添加到应用程序中
//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;
//form.component.jsx
类形式扩展了React.Component{
handleSubmit=(事件)=>{
event.preventDefault();
取('http://localhost:5000/results', {
方法:“POST”,
标题:{
“内容类型”:“应用程序/json”
},
正文:JSON.stringify(this.state)
}).then((response)=>response.json())
。然后((json)=>{
console.log(json)
这个.props.history.push(“/谢谢”);
})
.catch((错误)=>console.log(错误消息));
};
导出默认表单;
//app.js
从“react router dom”导入{BrowserRouter,Route};
类应用程序扩展了React.Component{
返回(
);
}
导出默认应用程序;
您必须在函数渲染中返回
以重定向。因此,我建议您使用组件
设置一个模式,并在函数渲染中渲染它
例如:
state={
modal: null,
}
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)
this.setState({modal: <Redirect to="/thank-you/" />})
return response.json();
});
}
catch (error){
console.log(error);
}
}
render() {
return <div>
...
{this.state.modal}
</div>
}
状态={
模态:空,
}
handleSubmit=异步事件=>{
event.preventDefault();
试一试{
待命http://localhost:5000/results', {
方法:“POST”,
标题:{
“内容类型”:“应用程序/json”
},
正文:JSON.stringify(this.state)
}).然后(功能(响应){
console.log(响应)
this.setState({modal:})
返回response.json();
});
}
捕获(错误){
console.log(错误);
}
}
render(){
返回
...
{this.state.modal}
}
您必须在函数渲染中返回
以重定向。因此,我建议您使用组件
设置一个模式,并在函数渲染中渲染它
例如:
state={
modal: null,
}
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)
this.setState({modal: <Redirect to="/thank-you/" />})
return response.json();
});
}
catch (error){
console.log(error);
}
}
render() {
return <div>
...
{this.state.modal}
</div>
}
状态={
模态:空,
}
handleSubmit=异步事件=>{
event.preventDefault();
试一试{
待命http://localhost:5000/results', {
方法:“POST”,
标题:{
“内容类型”:“应用程序/json”
},
正文:JSON.stringify(this.state)
}).然后(功能(响应){
console.log(响应)
this.setState({modal:})
返回response.json();
});
}
捕获(错误){
console.log(错误);
}
}
render(){
返回
...
{this.state.modal}
}
您不能使用重定向
组件以编程方式重定向用户。重定向
组件应在JSX中呈现,以使其生效并重定向应用程序
如果您使用的是功能组件,则可以使用useHistory
hook fromreact router dom
在表单提交后重定向用户
import { useHistory } from 'react-router-dom';
function MyComponent() {
...
const routerHistory = useHistory();
const handleSubmit = async event => {
event.preventDefault();
try {
...
routerHistory.push('/new-route');
}
catch (error){
console.log(error);
}
}
...
}
对于类组件,您可以使用从react路由器传递到直接子组件的历史
道具
class MyComponent extends React.Component {
...
handleSubmit = async event => {
event.preventDefault();
try {
...
this.props.history.push('/new-route');
}
catch (error){
console.log(error);
}
}
...
}
如果类组件中未定义history
prop,则可以使用withRouter
高阶组件来确保将路由器prop传递给组件
import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
...
}
export default withRouter(MyComponent);
旁注:在
handleSubmit()
方法中,您将async wait
语法与promise-chaining
混合使用。请使用其中一种,但不要同时使用两者。我建议您使用async wait
语法
只需使用asyncwait
语法,handleSubmit()
方法的编写如下所示:
handleSubmit = async event => {
event.preventDefault();
try {
const requestData = {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state)
};
const response = await fetch('http://localhost:5000/results', requestData);
const data = await response.json();
// do something with the data returned from the server as
// a result of POSt request
...
// redirect
this.props.history.push('/thank-you');
} catch (error) {
console.log(error);
}
}
您不能使用
重定向
组件以编程方式重定向用户。重定向
组件应在JSX中呈现,以使其生效并重定向应用程序
如果您使用的是功能组件,则可以使用useHistory
hook fromreact router dom
在表单提交后重定向用户
import { useHistory } from 'react-router-dom';
function MyComponent() {
...
const routerHistory = useHistory();
const handleSubmit = async event => {
event.preventDefault();
try {
...
routerHistory.push('/new-route');
}
catch (error){
console.log(error);
}
}
...
}
对于类组件,您可以使用从react路由器传递到直接子组件的历史
道具
class MyComponent extends React.Component {
...
handleSubmit = async event => {
event.preventDefault();
try {
...
this.props.history.push('/new-route');
}
catch (error){
console.log(error);
}
}
...
}
如果类组件中未定义history
prop,则可以使用withRouter
高阶组件来确保将路由器prop传递给组件
import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
...
}
export default withRouter(MyComponent);
旁注:在
handleSubmit()
方法中,您将async wait
语法与promise-chaining
混合使用。请使用其中一种,但不要同时使用两者。我建议您使用async wait
语法
只需使用asyncwait
语法,handleSubmit()
方法的编写如下所示:
handleSubmit = async event => {
event.preventDefault();
try {
const requestData = {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state)
};
const response = await fetch('http://localhost:5000/results', requestData);
const data = await response.json();
// do something with the data returned from the server as
// a result of POSt request
...
// redirect
this.props.history.push('/thank-you');
} catch (error) {
console.log(error);
}
}
在.then()
中,设置一个状态变量,如this.setState({redirect:true})
(使用一个箭头函数进行回调,这样就不会丢失正确的this
)。现在,您可以简单地将{this.state.redirect&}
添加到组件中。(还要注意,您可以使用event.target.getAttribute('action'))
要从表单中获取url,或者从
中删除操作属性。然后()
,设置一个状态变量,如this.setState({redirect:true})
(使用箭头函数进行回调,这样就不会丢失正确的this
)。现在您只需添加{this.state.redirect&&}
到您的组件。(还要注意,您可以使用ev。)