如何在响应时解决此警告消息“修复,取消所有订阅以及componentWillUnmount方法中的异步任务”

时间:2019-05-25 07:28:10

标签: reactjs

我正面临以下警告:

  

无法在已卸载的组件上执行React状态更新。这是空操作,但它表明应用程序中发生内存泄漏。要修复,取消所有订阅和componentWillUnmount方法中的异步任务。

当我单击“提交”按钮时,即正在调用axios时,会显示它。

我确实尝试过同步调用axios,但问题仍然存在。

import React, {Component} from 'react'
import Button from '../../../components/UI/Button/Button'
import axios from '../../../axios-orders'
import classes from './ContactData.module.css'

import Spinner from '../../../components/UI/Spinner/Spinner'
class ContactData extends Component {


    state = {
        loading : false,
        name : '',
        email : '',
        address : {
            street : '',
            postalCode : ''
        }
    }


    componentWillUnmount(){
        console.log('contact will unmount');
    }
    componentDidUpdate(){
        console.log('contact did update');
    }

    placeOrder = async (order) => {
        let res = await axios.post('/orders.json' , order);
        let { data } = await res.data;
        this.setState({
            loading : false
        })
    };
    orderHandler = (e) => {
        e.preventDefault();

        // this.setState({
        //     loading : true
        // })
        const order = {
            ingredients : this.props.ingredients,
            price: this.props.totalPrice,
            customer : {
                name : 'sazzad',
                addres : {
                    road : 'xdf',
                    country : 'BD'
                },
                email : 'aaa@gmail.com'
            },
            deliveryMethod : 'fastest'
        }

        this.placeOrder(order)
    }
    render(){

        let form = (
            <form>
                <input className={classes.Input} type="text" name="name" placeholder="Your Name" />
                <input className={classes.Input} type="email" name="email" placeholder="Your Mail" />
                <input className={classes.Input} type="text" name="street" placeholder="Street" />
                <input className={classes.Input} type="text" name="postal" placeholder="Postal Code" />
                <Button btnType="Success" clicked={this.orderHandler}>ORDER NOW</Button>
            </form>
        );

        if(this.state.loading){
            form = <Spinner />
        }
        return (

        <div className={classes.ContactData}>
            <h4>Enter your contact information</h4>
            {form}
        </div>
        );
    }
}

export default ContactData;

0 个答案:

没有答案