【问题标题】:Memory leak warning when using Redirect使用重定向时的内存泄漏警告
【发布时间】:2020-06-11 05:23:16
【问题描述】:

我使用 Firebase 通过 React 和 Redux 进行身份验证。在我使用 Redirect 之前,注册组件可以正常工作。

我在布局组件中有componentDidMountcomponentWillUnmount,并在Route App.js 中使用Redirect

如何解决内存泄漏警告问题?

布局组件

unsubscribeFromAuth = null;

componentDidMount() {
    const { setCurrentUser } = this.props;
    this.unsubscribeFromAuth = auth.onAuthStateChanged(async (userAuth) => {
        if (userAuth) {
            const userRef = await createUserProfileDocument(userAuth);

            userRef.onSnapshot((snapShot) => {
                setCurrentUser(
                    {
                        id: snapShot.id,
                        ...snapShot.data(),
                    },
                    () => {
                        console.log(this.state);
                    }
                );
            });
        }

        setCurrentUser(userAuth);
    });
}

// Close subscription
componentWillUnmount() {
    this.unsubscribeFromAuth();
}

布局组件中的 Redux

const mapDispatchToProps = (dispatch) => {
    return {
        setCurrentUser: (user) => dispatch(setCurrentUser(user)),
    };
};

App.js

<Route
    exact
    path='/signinsignup'
    render={() =>
    currentUser ? <Redirect to='/' /> : <SignInAndSignUpPage />
    }
/>

【问题讨论】:

    标签: reactjs firebase redirect redux react-redux


    【解决方案1】:

    您还需要取消订阅userRef.onSnapshot

    unsubscribeFromAuth = null;
    unsubscribeFromOnSnapshot = null
    
    componentDidMount() {
        const { setCurrentUser } = this.props;
        this.unsubscribeFromAuth = auth.onAuthStateChanged(async (userAuth) => {
            if (userAuth) {
                const userRef = await createUserProfileDocument(userAuth);
    
                this.unsubscribeFromOnSnapshot = userRef.onSnapshot((snapShot) => {
                    setCurrentUser(
                        {
                            id: snapShot.id,
                            ...snapShot.data(),
                        },
                        () => {
                            console.log(this.state);
                        }
                    );
                });
            }
    
            setCurrentUser(userAuth);
        });
    }
    
    // Close subscription
    componentWillUnmount() {
        this.unsubscribeFromAuth();
        if (this.unsubscribeFromOnSnapshot) {
            this.unsubscribeFromOnSnapshot();
        }
    }
    

    【讨论】:

    • 感谢您的回答,但仍然显示错误。
    猜你喜欢
    • 2011-10-23
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 2016-05-22
    • 2010-12-05
    • 1970-01-01
    相关资源
    最近更新 更多