使用Stack Navigator返回时刷新上一页的最佳方法是什么。在我返回的页面上似乎没有触发生命周期挂钩。我只是使用基本示例和this.props.navigation.goBack()
答案 0 :(得分:2)
您可以为此使用addListener
componentDidMount() {
this.props.navigation.addListener(
'didFocus',
payload => {
this.forceUpdate();
}
);
}
答案 1 :(得分:1)
好的,我在reddit上找到了答案。https://www.reddit.com/r/reactnative/comments/69xm4p/react_navigation_tab_change_event/
我使用hooonkos onNavigationStateChange方法使用它粘贴下面创建的示例。我没有拿出这个解决方案所有的功劳应该归到hooonko。
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import { TabNavigator } from 'react-navigation';
import Icon from 'react-native-vector-icons/FontAwesome';
class MyHomeScreen extends React.Component {
static navigationOptions = {
tabBarLabel: 'Home',
// Note: By default the icon is only shown on iOS. Search the showIcon option below.
tabBarIcon: ({ tintColor }) => (
<Icon
name="home"
size={30}
color={tintColor}
/>
),
};
_myHomeFunction = () => {
alert('Here is home tab!');
}
componentWillReceiveProps(newProps) {
if (newProps.screenProps.route_index === 0) {
this._myHomeFunction();
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>
Home
</Text>
</View>
);
}
}
class MyRocketScreen extends React.Component {
static navigationOptions = {
tabBarLabel: 'Rocket',
tabBarIcon: ({ tintColor }) => (
<Icon
name="rocket"
size={30}
color={tintColor}
/>
),
};
_myRocketFunction = () => {
alert('Here is rocket tab!');
}
componentWillReceiveProps(newProps) {
if (newProps.screenProps.route_index === 1) {
this._myRocketFunction();
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>
Rocket
</Text>
</View>
);
}
}
const MyApp = TabNavigator({
Home: {
screen: MyHomeScreen,
},
Rocket: {
screen: MyRocketScreen,
},
}, {
tabBarOptions: {
activeTintColor: '#e91e63',
},
});
class rn extends Component {
_onNavigationStateChange = (prevState, newState) => {
this.setState({...this.state, route_index: newState.index});
}
render() {
return (
<MyApp onNavigationStateChange={this._onNavigationStateChange} screenProps={this.state} />
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
text: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
AppRegistry.registerComponent('rn', () => rn);
答案 2 :(得分:0)
在react功能组件中,您可以这样操作:
const SomeComponent = (props) => {
useEffect(() => {
props.navigation.addListener(
'didFocus',
payload => {
//call some action here
}
);
}, [])
}
每当您降落到组件上时,都会触发上述效果,只要您从导航堆栈返回并且想要触发api或进行一些计算,它就会起作用。