提升表单提交数据的反应

时间:2020-09-21 12:11:35

标签: reactjs

我有一个表单组件,当前我向URL提交表单并从成功的请求中返回数据,但是由于该组件已模块化,因此返回的数据无法由我的应用程序中的其他组件访问,我想知道我是否可以将表单提交请求逻辑保留在此组件(标题)中,但可以将响应数据提升到在父级别设置的功能,该功能可以存储在状态中并与我的应用程序中的其他组件共享。

目前,我的解决方案正在按预期工作,因为data参数返回了表单提交的TypeError: Cannot read property 'props' of undefined,并指向this.props.onFormSubmit(res.data)

index.js(父级):

import React from "react"
import Header from '../components/content/header';

class IndexPage extends React.Component {

    constructor(props) {
      super(props);
  
      this.onFormSubmit = this.onFormSubmit.bind(this);
  
      this.state = {
          sleep_data: [],
      }
    }

    onFormSubmit(e, data){
        e.preventDefault();
        console.log(e)
        console.log(data) // undefined
    }

    render() {
        const sleep = this.state.sleep_data || [];
        const {code, state} = queryString.parse(location.search)

        return (
            <Layout>
              <SEO title="Home" />
              <Header url={location.href} code={code} state={state} sleep_data={this.state.sleep_data} onFormSubmit={this.onFormSubmit}/>
            </Layout>
          )
        }
    }
      
export default IndexPage;

标题(表格):

import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import { DateTime } from 'luxon';
import axios from 'axios';
var dt = DateTime.local();
import "react-datepicker/dist/react-datepicker.css";

class Header extends Component {
    constructor(props) {
        super(props);

        this.setStartDate = this.setStartDate.bind(this);
        this.setEndDate = this.setEndDate.bind(this);
        this.onFormSubmit = this.onFormSubmit.bind(this);

        this.state = {
            startDate: '',
            endDate: ''
        }
    }

    componentDidMount(){
        this.setState({
            startDate: new DateTime.local().minus({ days: 7 }).ts,
            endDate: dt.toMillis(new Date())
        });
    }

    onFormSubmit(e) {
        e.preventDefault();
        console.log("onFormSubmit()")
        console.log(this.state.startDate)
        console.log(this.state.endDate)
        axios.get('http://localhost:3000/tokens', {
            params: {
                code: this.props.code,
                state: this.props.state,
                start_date: DateTime.fromMillis(this.state.startDate).toISODate(),
                end_date: DateTime.fromMillis(this.state.endDate).toISODate()
            }
        }).then(function(res){
            console.log(res)
            console.log(res.data)
            this.props.onFormSubmit(res.data)
        }).catch(function(err){
            console.log(err) // TypeError: Cannot read property 'props' of undefined
        })
    }

    render() {
        return ( 
            <div className="flex-row">
                <h3 className="text-low-purple-300"><u>Generate your report in three clicks</u></h3>
                <ol>
                    <li className="text-lg font-bold mb-5 mt-5 text-low-purple-200">Step 1: Pick a date range</li>
                    <form onSubmit={ this.onFormSubmit }>
                        <div className="w-full px-3 mb-5">
                            <label className="mr-4">Start Date:</label>
                            <DatePicker selected={this.state.startDate} onChange={this.setStartDate} className="text-black text-center rounded-md p-2" name="startDate" />
                        </div>
                        <div className="w-full px-3">
                            <label className="mr-5">End Date:</label>
                            <DatePicker selected={this.state.endDate} onChange={this.setEndDate} className="text-black text-center rounded-md p-2" name="endDate" />
                        </div>
                        <li className="text-lg font-bold mt-5 text-low-purple-200">Step 2: Click submit</li>
                        
                        <button className="text-xl font-bold bg-mid-purple-500 hover:bg-mid-purple-700 w-64 py-5 px-5 rounded-md">Run Free Analysis</button>
                    </form>
                </ol>
            </div>
        )
    }
}

export default Header;

1 个答案:

答案 0 :(得分:1)

您需要在.then()和.catch()方法内使用箭头函数,才能使用组件的this。在function () {}中,this具有函数()的范围。

onFormSubmit(e) {
        e.preventDefault();
        console.log("onFormSubmit()")
        console.log(this.state.startDate)
        console.log(this.state.endDate)
        axios.get('http://localhost:3000/tokens', {
            params: {
                code: this.props.code,
                state: this.props.state,
                start_date: DateTime.fromMillis(this.state.startDate).toISODate(),
                end_date: DateTime.fromMillis(this.state.endDate).toISODate()
            }
        }).then((res) => {
            console.log(res)
            console.log(res.data)
            this.props.onFormSubmit(res.data)
        }).catch((err) => {
            console.log(err) // TypeError: Cannot read property 'props' of undefined
            // you may use `this` here as well, if needed
        })
    }

了解更多here