React native 在页面导航后继续执行componentDidUpdate
我正在使用React-Native、React-Navigation和Redux。我有一个注册页面,它将用户信息发送到服务器,并侦听令牌。一旦收到令牌,我将更改全局状态{userLoggedIn:true} 在我的组件中,我使用componentDidUpdate检查userLoggedIn是否为true,如果为true,那么我将重定向到“主页” 这很好,因为我被重定向到主页。然而,在主页本身,它正在不停地刷新。我检查了日志,发现componentDidUpdate仍在从register页面调用 因此,我有点困惑,为什么仍在调用componentDidUpdate?当它被导航到一个新页面后,它不会停止检查吗React native 在页面导航后继续执行componentDidUpdate,react-native,react-navigation,React Native,React Navigation,我正在使用React-Native、React-Navigation和Redux。我有一个注册页面,它将用户信息发送到服务器,并侦听令牌。一旦收到令牌,我将更改全局状态{userLoggedIn:true} 在我的组件中,我使用componentDidUpdate检查userLoggedIn是否为true,如果为true,那么我将重定向到“主页” 这很好,因为我被重定向到主页。然而,在主页本身,它正在不停地刷新。我检查了日志,发现componentDidUpdate仍在从register页面调用
编辑1:我意识到这不是componentDidUpdate的问题。我在render方法中插入了重定向条件,它也会导致无限循环。我不明白为什么它在导航到新页面时仍在尝试渲染。看起来你的注册页面在导航到主页后会不断获得新的道具和更新。我认为这是由于
导航
道具更新所致。在componentdiddupdate
中,您应该确保仅在一种情况下更改页面-当您的userLoggedIn
从false
更改为true
时
// component/register
class Register extends Component {
...
componentDidUpdate(prevProps){
console.log('componentDidUpdate from the register page')
if (this.props.people.userLoggedIn === true && prevProps.people.userLoggedIn === false) {
this.props.navigation.navigate('Main');
}
}
render(){
//sign up form
}
}
您可以使用来了解组件是否已聚焦。即使导航到另一页,上一页仍在堆栈中,只是隐藏而不是删除。因此,当道具或状态改变时,它仍将更新。。
// component/register
class Register extends Component {
...
componentDidUpdate(prevProps){
console.log('componentDidUpdate from the register page')
if (this.props.people.userLoggedIn === true && prevProps.people.userLoggedIn === false) {
this.props.navigation.navigate('Main');
}
}
render(){
//sign up form
}
}