gpt4 book ai didi

javascript - 警告 : Can't call setState (or forceUpdate) on an unmounted component

转载 作者:数据小太阳 更新时间:2023-10-29 03:48:23 28 4
gpt4 key购买 nike

我每次登录都会收到这个警告,

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.

这是我的代码:

授权页面.js

 handleLoginSubmit = (e) => {
e.preventDefault()
let { email,password } = this.state
const data = {
email : email,
password : password
}
fetch('http://localhost:3001/auth/login',{
method : 'post',
body : JSON.stringify(data),
headers : {
"Content-Type":"application/json"
}
}).then(res => res.json())
.then(data => {
if(data.success){
sessionStorage.setItem('userid',data.user.id)
sessionStorage.setItem('email',data.user.email)
}
this.setState({loginData : data,
userData : data,
email:"",
password:""})
if(data.token) {
Auth.authenticateUser(data.token)
this.props.history.push('/dashboard')
}
this.handleLoginMessage()
this.isUserAuthenticated()
})
}

export default withRouter(AuthPage)

使用 withRouter 这样我就可以访问我用来导航的 Prop this.props.history.push('/dashboard')如果我不使用 withRouter,我将无法访问 this.props

索引.js

const PrivateRoute = ({ component : Component, ...rest }) => {
return (
<Route {...rest} render = { props => (
Auth.isUserAuthenticated() ? (
<Component {...props} {...rest} />
) : (
<Redirect to = {{
pathname: '/',
state: { from: props.location }
}}/>
)
)}/>
)
}

const PropsRoute = ({ component : Component, ...rest }) => (
<Route {...rest} render = { props => (
<Component {...props} {...rest} />
)}/>
)

const Root = () => (
<BrowserRouter>
<Switch>
<PropsRoute exact path = "/" component = { AuthPage } />
<PrivateRoute path = "/dashboard" component = { DashboardPage } />
<Route path = "/logout" component = { LogoutFunction } />
<Route component = { () => <h1> Page Not Found </h1> } />
</Switch>
</BrowserRouter>
)

我认为问题出在我的 withRouter 上,我们如何在不使用 withRouter 的情况下访问 this.props ?

最佳答案

它是异步的

this.setState({
loginData : data,
userData : data,
email:"",
password:""
})

犯错误您可以使用 this._mount 检查组件是否已挂载或卸载

componentDidMount () {
this._mounted = true
}
componentWillUnmount () {
this._mounted = false
}
...
if(this._mounted) {
this.setState({
loginData : data,
userData : data,
email:"",
password:""
})
...

关于javascript - 警告 : Can't call setState (or forceUpdate) on an unmounted component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50504195/

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