首页 > 解决方案 > React.js (w/ Electron) 未安装组件状态更改警告

问题描述

我目前正在使用 React 构建一个 Electron 应用程序,并且我不断收到一个错误,即我的状态正在更改,而我的组件未安装。

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. in Start (created by Context.Consumer)

我已经查找了多个线程和有关此的问题,并且没有异步任务或方式可以让我认为我的 Start 组件中的状态正在发生变化,尽管也许其他人可能会看到我没有看到的东西。

我目前仅在此组件中使用状态来在将文件放入应用程序时使用反应路由器进行重定向。由于需要呈现 Redirect 组件才能发生重定向,因此我将其设置为 null 在我的状态下,然后在删除时将其更改为组件。这样我就可以简单地将状态放在组件的返回语句中。

商店.js:

import React, { useState } from "react";
import { Redirect } from "react-router-dom";
import drop from "../../assets/images/drop.svg";
import { ipcRenderer } from "electron";
import M from "materialize-css";

const Start = () => {
    const [redir, setRedir] = useState(null);

    document.ondragover = document.ondrop = (e) => {
        e.dataTransfer.dropEffect = "copy";
        e.preventDefault();
    };

    document.ondrop = (e) => {
        for (let file of e.dataTransfer.files) {
            // notify user about incompatible file types
            if (
                file.path.split(".").pop() !== "js" &&
                file.path.split(".").pop() !== "css" &&
                file.path.split(".").pop() !== "html" &&
                file.path.split(".").pop() !== "svg"
            ) {
                M.toast({
                    html: `"${file.path
                        .split("/")
                        .pop()}" could not be minified due to incompatible file type.`,
                });
            } else {
                ipcRenderer.send("file:add", file.path);
                setRedir(<Redirect to="/list" />);
            }
        }
        e.preventDefault();
    };

    // display toast for if file contains JSX
    ipcRenderer.on("minify:error-react", (e, data) => {
        M.toast({
            html: `${data.path
                .split("/")
                .pop()} could not be minified because the file contains JSX.`,
        });
    });

    return (
        <div className="start">
            <div className="start-drop">
                <img src={drop} draggable="false" alt="" />
                <p>Drop any HTML, CSS, JS, or SVG files here to minify</p>
            </div>
            {redir}
        </div>
    );
};

export default Start;

作为参考,这是用户在打开应用程序时看到的第一页。在此之前不应渲染任何其他组件(除了 App 组件),因为这只是一个路由。如果您需要更多上下文代码,请告诉我,我会添加它。

标签: javascriptreactjselectronstate

解决方案


推荐阅读