gpt4 book ai didi

reactjs - react 顶部加载栏警告 : Can't perform a React state update on an unmounted component

转载 作者:行者123 更新时间:2023-12-05 05:00:07 26 4
gpt4 key购买 nike

我想为顶部带有进度条的网站添加功能。并安装了依赖项“react-top-loading-bar”。它有效,但出现警告。

附言我已经复习过其他类似的主题,但对我来说没有效果

import React, {Component} from "react";
import {connect} from "react-redux";
import {auth} from "../store/actions/user";
import Loader from "../UI/Preloader/loader";
import LoadingBar from "react-top-loading-bar";


// Auth(Component, reload)

// This is an HOC component, on every route change I check if user is authenticated

// reload true means that if user is not authenticated it will be redirected to login page
// if reload is false it means user is already logged in and redirected to his dashboard
// if there is no reload user can access those pages without authentication

export default function (ComposedClass, reload) {

class AuthenticationCheck extends Component {

_isMounted = false;

state = {
loading: true,
progress: 0
};

//// checking if user is authenticated
componentDidMount() {
window.scrollTo(0, 0);

this._isMounted = true;

if(this._isMounted) {
setTimeout(() => {
this.setState({
progress: 100
})
}, 300);
}


if (this.props.user.authLogin && this.props.user.authLogin.id) {
this.setState({loading: false});
} else {
this.props.dispatch(auth());
}
}

UNSAFE_componentWillReceiveProps(nextProps) {

this.setState({loading: false});

if (!nextProps.user.authLogin.isAuth) {
if (reload) {
this.props.history.push("/login");
}
} else {
if (reload === false) {
this.props.history.push("/profile")
}
}
}

componentWillUnmount() {
this._isMounted = false;
}


render() {
if (this.state.loading) {
return <Loader/>
}
return (
<React.Fragment>
<LoadingBar
color='#45C0AE'
height={4}
progress={this.state.progress}
// loaderSpeed={1000}
onLoaderFinished={() => {}}
/>
<ComposedClass {...this.props} user={this.props.user}/>
</React.Fragment>
)
}
}

function mapStateToProps(state) {
return {
user: state.user_r
}
}

return connect(mapStateToProps)(AuthenticationCheck);
}

我尝试将上述方法与 (_ismounted) 一起使用,但它对我不起作用。

如果我同时快速改变路线,在进度条完成达到 100% 之前会出现警告。但是,如果我等待 1-2 秒直到进度条结束,然后更改路线 - 在这种情况下没有警告。

最佳答案

您还必须将检查添加到 UNSAFE_componentWillReceiveProps,因为它也会被调用,但组件已经消失。

  UNSAFE_componentWillReceiveProps(nextProps) {
if(!this._isMounted){return;}
this.setState({loading: false});

if (!nextProps.user.authLogin.isAuth) {
if (reload) {
this.props.history.push("/login");
}
} else {
if (reload === false) {
this.props.history.push("/profile")
}
}
}

componentWillUnmount() {
this._isMounted = false;
}

我还建议使用函数组件来使用更新的更好的方法来呈现它。还有一个不使用 UNSAFE_componentWillReceiveProps 的原因。也试试 componentDidUpdate .

关于reactjs - react 顶部加载栏警告 : Can't perform a React state update on an unmounted component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63219839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com