我正在使用reactnavigation
stackNavigtor作为根结构。
当我的应用加载时,它最初会根据intialRouteName安装一个组件 - 到目前为止这是好的。但是,当我打开我的slideMenu并导航到另一个屏幕时,即使我已经成功导航,我刚刚进入的组件也没有卸载并仍在后面渲染。
当然我可以使用我的初始组件中的this.state({})
来停止渲染,但问题是,我无法以这样的方式设置它,当我导航到另一个屏幕时,我会阻止渲染上一个屏幕。
/*
* LaunchScreen loads first
* I then navigate to Profile via (this.props.navigate('OpenDrawer')).
* - This opens CustomComponent and inside that, I select Profile
* When I navigate to Profile, The LaunchScreen is not unmounted
*/
export const SignedIn = StackNavigator({
LaunchScreen: {
screen: $LaunchScreen
},
Profile: {
screen: $Profile
},
EditProfile: {
screen: EditProfile
},
MyDoctors: {
screen: $Doctors
}
}, {
headerMode: "none",
mode: "modal",
initialRouteName: 'LaunchScreen' // this is the component that loads
});
export const HomeNav = StackNavigator({
Home: {
screen: SignedIn,
navigationOptions: {
gesturesEnabled: false
}
}
}, {
headerMode: "none",
mode: "modal",
initialRouteName: "Home", // we enter this route when the app loads.
});
const PrimaryNav = StackNavigator({
SignedIn: {
screen: HomeNav,
navigationOptions: {
gesturesEnabled: false
}
},
SignedOut: {
screen: SignedOut,
navigationOptions: {
gesturesEnabled: false
}
},
Loading: {
screen: Loading
}
}, {
headerMode: "none",
mode: "modal",
initialRouteName: "Loading",
});
export default PrimaryNav;
// ... Imports {}
export default class LaunchScreen extends PureComponent<*, State> {
constructor(props) {
super(props);
this.state = {
index: 0,
};
}
componentDidMount() {
};
_renderScene = ({ route }) => {
return (
<SimplePage
state = {this.state}
style = {{ backgroundColor: 'white' }}
type = {this.state.type}
updateIndex = {this.updateIndex.bind(this)}
/>
);
};
_renderHeader = props => {
/*
* "this.props.navigation.navigate('DrawerOpen')" opens the drawer from left side
*
*/
return (
<View>
<View style={styles.headerContainer}>
<TouchableHighlight onPress={() => this.props.navigation.navigate('DrawerOpen')} activeOpacity={1.0} underlayColor="rgba(253,138,94,0)">
</TouchableHighlight>
</View>
</View>
);
};
render() {
return (
<TabViewAnimated
style={[styles.container, this.props.style]}
navigationState={this.state}
renderScene={this._renderScene}
renderHeader={this._renderHeader}
/>
);
}
}
我想知道当我导航到另一个屏幕时如何卸载组件。
答案 0 :(得分:1)
您可以使用以下条件:
render() {
return (
<View>
<View style={styles.headerContainer}>
{ this.state.someCondition ?
<SomeCoponent onPress={() => this.onPress}/> :
<AnotherComponent onPress={() => this.onPress}/>
}
</View>
</View>
)
}
查看react-router:
render() {
return (
<View>
<View style={styles.headerContainer}>
<Router>
<Route exact path="/" component={HomeComponent}/>
<Route path="/news" component={NewsFeedComponent}/>
<Route exact path="/another" component={AnotherComponent}/>
</Router>
</View>
</View>
)
}