简体   繁体   English

React.js - 表单提交,将数据发布到后端并重定向页面

[英]React.js - on form submit, post data to backend and redirect page

I am working on my first React project.我正在做我的第一个 React 项目。

I'd like to do 2 things when a form is submitted:提交表单时,我想做两件事:

  1. post form data to the backend将表单数据发布到后端
  2. redirect to a thank-you page重定向到感谢页面

I am able to post the form data to the backend with handleSubmit (code below), but looking for a way to incorporate redirect.我可以使用 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);
        }
    }

This is how the handleSubmit is call on the form这就是 handleSubmit 在表单上的调用方式

<form onSubmit={this.handleSubmit} 
             action="http://localhost:5000/results" method="post"
             >

This is what I'd like to incorporate as part of handleSubmit这是我想作为 handleSubmit 的一部分合并的内容

<Redirect  to="/thank-you/" />

Edit: withRouter/this.props.history.push编辑: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);

Edit 2: rewrite handleSubmit, add BrowserRouter to App编辑 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;

You can't use Redirect component to programmatically redirect the user.您不能使用Redirect组件以编程方式重定向用户。 Redirect component should be rendered in the JSX in order for it to take effect and redirect the app. Redirect组件应在 JSX 中呈现,以使其生效并重定向应用程序。

If you are using functional component, than you can use useHistory hook from react-router-dom to redirect the user after form submission.如果您使用的是功能组件,那么您可以使用react-router-dom useHistory钩子在表单提交后重定向用户。

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

   ...
}

In case of class component, you can use history prop that is passed from the react router to the direct child components.在类组件的情况下,您可以使用从反应路由器传递到直接子组件的history道具。

class MyComponent extends React.Component {
   ...

   handleSubmit = async event => {
        event.preventDefault();
        try {
            ...
            this.props.history.push('/new-route');
        }
        catch (error){
            console.log(error);
        }
    }

   ...
}

If history prop is not defined in your class component, then you can use withRouter higher-order component to ensure that router props are passed to your component.如果您的类组件中没有定义history prop,那么您可以使用withRouter高阶组件来确保将路由器 props 传递给您的组件。

import { withRouter } from 'react-router-dom';

class MyComponent extends React.Component {
   ...
}

export default withRouter(MyComponent);

Side note: Inside handleSubmit() method, you have mixed async-await syntax with promise-chaining .旁注:handleSubmit()方法中,您将async-await语法与promise-chaining混合使用。 Use either one of them but not both at the same time.使用其中之一,但不要同时使用两者。 I suggest that you use async-await syntax.我建议您使用async-await语法。

Using just async-await syntax, handleSubmit() method could be written like as shown below:使用async-await语法, 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);
     }
}

You must return <Redirect to="/thank-you/" /> in function render to redirect.您必须在函数 render 中返回<Redirect to="/thank-you/" />才能重定向。 So, i suggest you should set a modal with component <Redirect to="/thank-you/" /> and render it in function render.所以,我建议你应该使用组件<Redirect to="/thank-you/" />设置一个模态并在函数渲染中渲染它。

Example:例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM