我正在尝试为我的应用程序构建专用路由器组件。这是我的代码。
const history = createBrowserHistory()
class PrivateRoute extends Component {
constructor(props) {
super(props);
this.state={auth:false}
}
async componentDidMount() {
let userCheckResult = await checkUser(localStorage.getItem('token'), URL_ENDPOINTS.USER_CHECK);
if (!isEmptyObj(userCheckResult)) {
this.setState({auth:true})
}
}
render() {
if (this.state.auth) {
return (
<Route {...this.rest} {...this.props} component={this.props.component} />
)
} else {
return (
<Redirect to={{ pathname: '/login' }} />
)
}
}
}
class App extends Component {
render() {
return (
<Provider store={store}>
<Header />
<Router history={history}>
<Switch>
<Route path="/login" exact component={LoginPage} />
<PrivateRoute exact path="/statements" component={Statements} />
</Switch>
</Router>
<Footer />
</Provider>
)
}
}
export default App
在我的componentDidMount
中,我更新了我的状态(但它没有改变)。我试图在我的渲染函数中引用该状态。
因为它不会改变状态。它也不会改变经过身份验证的用户的路由。
它在控制台上显示此错误。
index.js:1446 Warning: Can't perform a React state update 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.
如果有人能够纠正我的解决方案,那将非常有帮助。
默认情况下,您的州设置为auth: false
。如果您的this.state.auth
为假,您可以立即重定向。这意味着组件将始终重定向。
您最终在componentDidMount
中的异步请求之后设置状态,但此时您已经重定向,并且此组件可能已经长时间卸载,因此导致在卸载组件后尝试设置状态的警告。
要解决此问题,我建议在您的州中添加第二个变量,以跟踪您是否已执行身份验证请求。如果尚未执行身份验证,则在渲染中您不应重定向(可能显示某种微调器)。执行完毕后,您可以根据身份验证确定是否应该重定向用户。