Aid*_*rty 9 react-native react-navigation
什么是使用Stack Navigator返回时刷新上一页的最佳方法.在我返回的页面上似乎没有触发生命周期挂钩.我只是使用基本的例子和this.props.navigation.goBack()
Mah*_*our 16
你可以用addListener这个
componentDidMount() {
this.props.navigation.addListener(
'didFocus',
payload => {
this.forceUpdate();
}
);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
在反应功能组件中你可以这样做:
const SomeComponent = (props) => {
useEffect(() => {
props.navigation.addListener(
'didFocus',
payload => {
//call some action here
}
);
}, [])
}
Run Code Online (Sandbox Code Playgroud)
每当您登陆该组件时,上述效果都会触发,每当您从导航堆栈返回并且想要触发 api 或进行一些计算时,它都会起作用。
好的,我在 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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6579 次 |
| 最近记录: |