gpt4 book ai didi

reactjs - 对已卸载组件中的 setState 使用react警告

转载 作者:行者123 更新时间:2023-12-03 12:59:52 25 4
gpt4 key购买 nike

我收到此错误:

warning.js:33 Warning: Can't call setState (or forceUpdate) 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 the componentWillUnmount method.

但我没有使用 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 方法。我真的不知道为什么这个警告不断弹出,任何信息都会有帮助。

<小时/>

2018 年 5 月 23 日更新:

为了消除错误并仍然传递 Prop ,我做了两件事:

1) 我选择在父 App 组件中使用两个高阶函数,而不是使用 HOC。一个高阶函数是用于传递 props,另一个是检查身份验证。除了浏览器历史记录之外,我在传递任何 props 时都遇到了麻烦,因此使用了下面的 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} />

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

另外,这里有一个关于 Stack Overflow 的很好的解释。

最后,我使用 React Router 4 文档中的这段代码作为我上面所做的事情的模板。我确信下面的内容更清晰,但我仍在学习,我所做的对我来说更有意义。

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

最佳答案

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

查看此类错误的一个好习惯是绘制应用程序流程并查看何时调用 setState

如果我是你,我会改变的另一件事是用 componentDidMount 而不是 componentWillMount 来检查一些数据。考虑到 Facebook 已弃用此功能。

This lifecycle was previously named componentWillMount. That name will continue to work until version 17. Use the rename-unsafe-lifecycles codemod to automatically update your components.

Reactjs component documentation

关于reactjs - 对已卸载组件中的 setState 使用react警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50029468/

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