小编典典

在卸载的组件中反应有关setState的警告

reactjs

我收到此错误:

warning.js:33警告:无法在已卸载的组件上调用setState(或forceUpdate)。这是空操作,但它表明应用程序中发生内存泄漏。要解决此问题,请在componentWillUnmount方法中取消所有订阅和异步任务。

但是我没有使用componentWillUnMount方法。

我正在使用HOC来确保用户在访问其/ account路由之前已通过身份验证。

这是路线:

<StyleRoute props={this.props} path="/account" component= 
{RequireAuth(Account)} />

其中RequireAuth是HOC。这是HOC:

 import { withRouter } from 'react-router';

export default function RequireAuth(Component) {

  return class AuthenticatedComponent extends React.Component {

    componentWillMount() {
      this.checkAuth();
    }

    checkAuth() {
      if ( ! this.props.isAuthenticated) {
        this.props.history.push(`/`);
      }
    }

    render() {
      return this.props.isAuthenticated
        ? <Component { ...this.props } />
        : null;
    }

  }

  return withRouter(AuthenticatedComponent);
}

该代码按预期工作,但是在呈现/
account时出现该错误。如您所见,在我的直接代码中,没有任何地方有componentWillUnMount方法。我真的很茫然,为什么这个警告不断弹出,任何信息都会有所帮助。


更新5/23/18:

为了摆脱错误并仍然保留道具,我做了两件事:

1)我选择在父App组件中具有两个高阶函数,而不是使用HOC。一个高阶函数用于传递道具,另一个用于检查身份验证。除了浏览器历史记录外,传递其他道具时遇到麻烦,因此下面的renderProps函数。

renderProps = (Component, props) => {
  return (
      <Component {...props} />
    );
}

checkAuth = (Component, props) => {
    if (props.isAuthenticated) {
        return <Component {...props} />
    }
    if (!props.isAuthenticated) {
        return <Redirect to='/' />
    }
}

2)要使用这些,我必须在Route中使用用户渲染,而不是组件。

//I could pass props doing this, sending them through the above functions
<Route exact path="/sitter-dashboard" render={ () => this.checkAuth(SitterDashboard, this.props) } />
<Route exact path={"/account/user"} render={() => this.renderProps(User, this.props)} />

//I couldn't pass props doing this
<Route {...this.props} exact path="/messages" component={Messages} />

这是有关路由器vs组件作为Route渲染方法的文档:https : //reacttraining.com/react-
router/web/api/Route/route-render-methods

另外,这是关于堆栈溢出的一个很好的解释

最后,我使用了React Router 4文档中的代码作为我上面所做的模板。我敢肯定下面的内容比较干净,但是我仍在学习,所做的事情对我来说更有意义。

const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
  {...rest}
  render={props =>
  fakeAuth.isAuthenticated ? (
       <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/login",
            state: { from: props.location }
          }}
        />
      )
    }
  />
);

阅读 277

收藏
2020-07-22

共1个答案

小编典典

我之前也有同样的错误,它是由使用ref标签的组件生成的,并且有一些手动操作。

看到这些错误的一个好习惯是吸引您的应用程序流,并查看调用的时间setState

如果您是我,我会改变的另一件事是componentDidMount代替componentWillMount检查某些数据。考虑到fb不建议使用此功能。

该生命周期以前称为componentWillMount。该名称将一直使用到第17版。使用redirect-unsafe-lifecycles
codemod自动更新您的组件。

ReactJS组件文档

2020-07-22