【问题标题】:React react-switch Can't perform a React state update on an unmounted componentReact react-switch 无法在未安装的组件上执行 React 状态更新
【发布时间】:2020-08-03 00:21:09
【问题描述】:

我正在尝试使用 DataTable 和 react-switch 编写 React 组件。

好像可以,但是当我看到开发者控制台时,出现错误:

警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请在 componentWillUnmount 方法中取消所有订阅和异步任务。

该错误仅在我“拖动”开关时显示。如果我只点击开关,没有错误。

import React from 'react';
import { authenticationService } from '../../helpers/AuthenticationService';
import axios from 'axios';
import DataTable from 'react-data-table-component';
import Switch from "react-switch";


class ProductEshop extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            isCancelled: false,
            data: [],
            checked: false
        }
    }


    handleButtonClick = (state, row) => {

    this.setState({
            data: this.state.data.map((item, index) =>
                item.eshopId == row.eshopId ? { ...item, isActive: !item.isActive } : item,
            )
     })
    };

    componentDidMount() {
        const currentUser = authenticationService.currentUserValue;

        axios.get('/api/product/' + this.props.id + '/eshops', { headers: { "Authorization": `Bearer ${currentUser.token}` } }).then(res => {
            this.setState({ data: res.data });
        }).catch(err => {
            console.log(err);
        });
    }

    render() {
        const columns = (clickHandler => [

            {
                cell: (row) => <Switch onChange={(e) => clickHandler(e, row)} checked={row.isActive} />
            },
            {
                name: 'Název',
                selector: 'name',
                sortable: true,
            }
        ]);

        return (<div>
            <DataTable
                title="Products"
                data={this.state.data}
                columns={columns(this.handleButtonClick)}
                onRowSelected={this.handleChange}
                paginationComponentOptions={this.state.paggination}
                pagination
                dense
            />
        </div>)
    }
}

export default (ProductEshop)

有人可以帮忙吗?

更新:错误是在handleButtonClick中创建的

【问题讨论】:

    标签: reactjs datatable


    【解决方案1】:

    这是因为 this.setState 在异步进程中被调用。这意味着即使您卸载组件 Axios 也会尝试执行then,这就是您收到警告的原因。您需要取消componentWillUnmount上的请求

      componentDidMount () {
        this.axiosCancelSource = axios.CancelToken.source()
    
       axios.get('/api/product/' + this.props.id + '/eshops', 
      { headers: { "Authorization": `Bearer ${currentUser.token}` }, 
        cancelToken: this.axiosCancelSource.token })
       .then(res => {
                this.setState({ data: res.data });
            }).catch(err => {
                console.log(err);
          });
      }
    
      componentWillUnmount () {
        this.axiosCancelSource.cancel('Axios request canceled.')
      }
    

    【讨论】:

    • 谢谢,但消息仍然显示。我不认为问题出在axios,因为错误是在handleButtonClick中创建的。
    猜你喜欢
    • 2020-09-04
    • 2021-07-01
    • 2020-11-21
    • 2021-11-30
    • 2020-09-03
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2023-02-11
    相关资源
    最近更新 更多