React-native componentWillMount 不调用
React-native componentWillMount not calling
我是 react-native 的新手,我的堆栈中有两个屏幕。登录和主页。
我想通过主页上的按钮返回登录。
我正在写这段代码
this.props.navigation.navigate('loginScreen')
但在登录屏幕中 componentWillMount 方法未调用。当用户从家里进入登录屏幕时,我想重置我的表单。
有人可以帮我吗?
提前致谢。
要从主页登录返回,如果屏幕紧接在home
之前,您应该使用this.props.navigation.goBack()
。
其次,你不应该使用 componentWillMount
,因为它已被弃用,将从 React 17 中删除。而是使用 componentDidMount
由于组件已经挂载,因此不会再次调用 React 生命周期事件 componentDidMount
。因此你应该使用 react-navigation
listeners didFocus
事件。
didFocus: the screen focused (if there was a transition, the transition completed)
componentDidMount () {
this._onFocusListener = this.props.navigation.addListener('didFocus', (payload) => {
// Perform the reset action here
});
}
由于您的主页和登录屏幕都在同一个 StackNavigator 下,当您从主页返回到登录时状态保持不变,因为组件没有卸载。解决这个问题的推荐方法是使用 react-navigation 的 SwitchNavigator。阅读下面文档中非常有用的部分
https://reactnavigation.org/docs/en/auth-flow.html
You may not be familiar with SwitchNavigator yet. The purpose of
SwitchNavigator is to only ever show one screen at a time. By default,
it does not handle back actions and it resets routes to their default
state when you switch away.
this.props.navigation.navigate('loginScreen')
不起作用,因为您现在处于 loginScreen
。
如果你想重新启动页面,这段代码不好。因为有循环!
正确代码:
当 navigate
到 loginScreen
从 home
使用:
this.props.navigation.push('loginScreen')
不在"componentWillMount"
完美的解决方案是使用 this.props.navigation.push('Login')
,我尝试使用 SwitchNavigator
但它没有为 header 提供 navigationOptions
。
我是 react-native 的新手,我的堆栈中有两个屏幕。登录和主页。
我想通过主页上的按钮返回登录。
我正在写这段代码
this.props.navigation.navigate('loginScreen')
但在登录屏幕中 componentWillMount 方法未调用。当用户从家里进入登录屏幕时,我想重置我的表单。
有人可以帮我吗?
提前致谢。
要从主页登录返回,如果屏幕紧接在home
之前,您应该使用this.props.navigation.goBack()
。
其次,你不应该使用 componentWillMount
,因为它已被弃用,将从 React 17 中删除。而是使用 componentDidMount
由于组件已经挂载,因此不会再次调用 React 生命周期事件 componentDidMount
。因此你应该使用 react-navigation
listeners didFocus
事件。
didFocus: the screen focused (if there was a transition, the transition completed)
componentDidMount () {
this._onFocusListener = this.props.navigation.addListener('didFocus', (payload) => {
// Perform the reset action here
});
}
由于您的主页和登录屏幕都在同一个 StackNavigator 下,当您从主页返回到登录时状态保持不变,因为组件没有卸载。解决这个问题的推荐方法是使用 react-navigation 的 SwitchNavigator。阅读下面文档中非常有用的部分
https://reactnavigation.org/docs/en/auth-flow.html
You may not be familiar with SwitchNavigator yet. The purpose of SwitchNavigator is to only ever show one screen at a time. By default, it does not handle back actions and it resets routes to their default state when you switch away.
this.props.navigation.navigate('loginScreen')
不起作用,因为您现在处于 loginScreen
。
如果你想重新启动页面,这段代码不好。因为有循环!
正确代码:
当 navigate
到 loginScreen
从 home
使用:
this.props.navigation.push('loginScreen')
不在"componentWillMount"
完美的解决方案是使用 this.props.navigation.push('Login')
,我尝试使用 SwitchNavigator
但它没有为 header 提供 navigationOptions
。