即使已安装组件,也会卸载setState警告

时间:2019-09-04 10:43:11

标签: javascript reactjs lifecycle

在我的ReactJS @ 15项目中,我遇到了卸载setState更改警告的问题,但是组件已经安装。

这是应用程序结构:

/app
  /container
     /veil
     /router
        /routed-view
        /other-routed-view

我还有一个“ 面纱管理器类”,它以这种方式触发附加到面纱组件的“ _toggle ”事件:

componentDidMount()
{
    VeilManager.i().on('toggle', this._toggle.bind(this));
}

_toggle(payload = {})
{
    const { veil = false, cb } = payload;
    this.setState({ isOpen: veil }, cb);
}

从路由视图中,我触发以下代码:

componentDidMount()
{
   VeilManager.i().toggle(this._otherFunc.bind(this));
}

在调试流程中,触发事件时,Veil组件被标记为已卸载,但完全没有意义,因为容器已在其子代中注册。

甚至更多,Veil组件会按预期做出反应,因此当VeilManager状态更改时,Veil会切换进出。

有什么建议吗?

扩展代码

// Veil.js
import { background, logo, veil }   from './Styles';
import React, { Component }         from 'react';
import VeilManager                  from './Manager';


export default class Veil extends Component
{
    constructor(props)
    {
        super(props);

        this.state = {
            isOpen: false
        };
    }

    componentDidMount()
    {
        VeilManager.i().on('toggle', this._toggle.bind(this));
    }

    _toggle(payload = {})
    {
        const { veil = false, cb } = payload;
        this.setState({ isOpen: veil }, cb);
    }

    /**
     * @override
     */
    render()
    {
        const { isOpen = false } = this.state;

        return (
            <div style={veil(isOpen)} className="veil-wrapper">
                <div style={logo} className="veil-wrapper__logo"/>
                <div style={background}/>
            </div>
        );
    }
}
// VeilManager.js
const { EventEmitter } = require('events');

/**
 * VeilManager singleton reference
 * @type {null}
 */
let $iManager = null;

/**
 * Handles the status of veil
 * @class   veil.Manager
 * @extends EventEmitter
 */
export default class Manager extends EventEmitter
{
    /**
     * @constructor
     */
    constructor()
    {
        super();
        this.isOpen = false;
    }

    /**
     * Toggles "isOpen" status
     * @param   {null|Function} cb  To execute after toggling
     */
    toggle(cb = null)
    {
        this.isOpen = !this.isOpen;
        this.emit('toggle', { veil: this.isOpen, cb });
    }

    /**
     * Returns the singleton instance of VeilManager
     * @return {null|Manager}   Singleton instance
     */
    static i()
    {
        $iManager = $iManager || new Manager();

        return $iManager;
    }
}
//Container.js
import 'react-s-alert/dist/s-alert-css-effects/slide.css';
import 'react-s-alert/dist/s-alert-default.css';
import { Redirect, Route, Switch }  from 'react-router-dom';
import React, { Component }         from 'react';
import Alert                        from 'react-s-alert';
import Aside                        from '@/components/Aside';
import Header                       from '@/components/Header';
import token                        from '@/orm/Token';
import Sidebar                      from '@/components/Sidebar';
import Veil                         from '@/components/Veil';

// VIEWS
import Clients              from '../../views/Clients/';
import Dashboard            from '@/views/Dashboard';

export default class Full extends Component
{
    /**
     * @override
     */
    render()
    {
        return (
            <div className="app">
                <Header />
                <div className="app-body">
                    <Sidebar {...this.props}/>
                    <main className="main">
                        <Veil/>
                        <div className="container-fluid">
                            { token.hasExpired()
                                ? <Redirect to="/login"/>
                                : <Switch>
                                    <Route path="/dashboard" name="Dashboard" component={Dashboard}/>
                                    <Route path="/clients" name="Clients" component={Clients}/>
                                    <Redirect to="/dashboard"/>
                                </Switch>
                            }
                        </div>
                    </main>
                    <Aside />
                </div>
                <Alert stack={{ limit : 3 }} />
            </div>
        );
    }
}
//Clients.js
import React, { Component } from 'react';
import onFetch              from '@/mixins/on-fetch';

/**
 * Clients view.
 */
export default class ClientsIndex extends Component
{
    /**
     * @constructor
     */
    constructor(props)
    {
        super(props);

        this._onFetch = onFetch;
    }

    /**
     * @override
     */
    componentDidMount()
    {
        this._onFetch();
    }

    /**
     * @override
     */
    render()
    {
        return (
            <div className="animated fadeIn">
                <div className="row">
                  ...
                </div>
            </div>
        );
    }
}
//mixin/on-fetch
import VeilManager from '@/components/Veil/Manager';

export default (cb = null) => {
    debugger;
    VeilManager.i().toggle(cb);
};

2 个答案:

答案 0 :(得分:1)

解决方案

正如评论中指出的那样,这是一个冒泡事件和状态传播的问题。

所做的更改:

for commit in commits:
    print("%s %s" % (commit.hexsha, commit.message.splitlines()[0]))
// Veil manager
...
toggle(cb = null)
{
    this.isOpen = !this.isOpen;
    const detail = { veil: this.isOpen, cb };
    window.dispatchEvent(new CustomEvent('veil-toggle', { bubbles: false, detail }));
}
...
// Veil
...
/**
 * @override
 */
constructor(props)
{
    super(props);

    this.state = {
        open: false
    };
}

/* istanbul ignore next */
componentWillReceiveProps(next)
{
    const open = next && !!next.open;
    this.setState({ open });
}

/**
 * @override
 */
render()
{
    return (
        <div style={veil(this.state.open)} className="veil-wrapper">
            <div style={logo} className="veil-wrapper__logo"/>
            <div style={background}/>
        </div>
    );
}
...

答案 1 :(得分:0)

根据上面的代码,如果在卸载Veil组件后veilManager触发了“ toggle”事件,那么您将遇到此错误。

您可以通过两种方式解决它:

  1. 在componentWillUnmount中删除“ onToggle”侦听器,以便在卸载Veil组件时,无需运行其处理程序。

  2. 或者,您可以在VeilComponent中保留变量this.mountState并创建一个单独的setStateSafe方法,该方法在调用setState之前检查MountedState。

    componentDidMount() {
        this.mountedState = true;
        VeilManager.i().on('toggle', this._toggle.bind(this));
    }

    _toggle(payload = {}) {
        const { veil = false, cb } = payload;
        this.setStateSafe({ isOpen: veil }, cb);
    }

    setStateSafe(nextState, cb) {
        if(this.stateMounted) {
             this.setState(nextState, cb);
        }
    }

我建议使用选项1,因为我们不应该为已卸载的组件调用切换处理程序。谢谢