我是 React Native 的新手,正在努力清理屏幕状态。
就像屏幕 A 有一些状态 --> 屏幕 B,回到屏幕 A,旧的状态是清晰的。我正在使用 React Navigation V5
我想做的是:
- 从
MainMap.js
导航到最后一个屏幕TripsListScreen.js
(整个过程是 4 个屏幕的堆栈,嵌套在抽屉中)后,我得到了所有存储在 Redux 存储中的数据,并将其显示在TripsListScreen
中。 - 问题是,当我按
TripsListScreen
中的add
按钮返回MainMap.js
时,它不会清理所有内容正如我所期望的那样。
这是 MainMap.js
的状态:
const initialState = {
hasMapPermission: false,
_userLocationDisplayed: null,
userLatitude: 0,
userLongitude: 0,
initial_UserLatitude: 0,
initial_UserLongitude: 0,
userLocationAddress: '',
destination: [],
destinationName: [],
destinationAddress: [],
destinationCoords: [],
destinationImageUri: [],
numOfInput:[0,1],
counter: 1,
wayPoints: [],
markers: [],
}
class MainMap extends React.Component{
constructor(props){
super(props);
this.state = initialState;
};
componentDidMount(){
console.log('Hello',this.props)
if(this.props.route.params === true){
this.setState(initialState)
}
this._requestUserLocation();
};
基本上,我尝试将一个 bool 参数从 TripsListScreen
传递到 MainMap
,如果该参数为 true,我会将所有状态设置回开头。但是,它并没有按预期工作。
这是TripsListScreen
:
//...
<Layout style={styles.bottom}>
<TouchableOpacity onPress={() => props.navigation.navigate('PlanningProcess', {
screen: 'MainMapScreen',
params: {doAddPlace: true}
})} style={styles.createTrip}>
<Layout style={styles.button} >
<Icon name='add' size={35} />
</Layout>
</TouchableOpacity>
</Layout>
//...
这是导航:
StackNavigator
:
const Stack = createStackNavigator();
const StackNavigator = (props) => {
return(
<Stack.Navigator screenOptions={{headerShown: false}}>
<Stack.Screen name='MainMapScreen' component={MainMap} />
<Stack.Screen name='TripDescription' component={TripDescription} />
<Stack.Screen name='TripsListDetailScreen' component={TripsListDetailScreen} />
<Stack.Screen
name='TripsListScreen'
component={TripsListScreen}
options={{
headerLeft: () => (<Icon style={{marginHorizontal: 30, marginTop: 30}} color='white' name='menu' size={30} onPress={() => props.navigation.dispatch(DrawerActions.openDrawer())}/>),
title:'Something'
}}
/>
</Stack.Navigator>
);
};
export default StackNavigator;
- 主要
导航器
:
const Navigator = () => {
return(
<NavigationContainer>
<Drawer.Navigator
statusBarAnimation='slide'
drawerContent={props =>
<DrawerContent {...props} />}>
<Drawer.Screen name='Welcome' component={WelcomeStackScreen} />
<Drawer.Screen name='TripsListScreen' component={TripsListScreen} />
<Drawer.Screen name='PlanningProcess' component={StackNavigators} />
</Drawer.Navigator>
</NavigationContainer>
);
};
export default Navigator;
这就是 MainMap
渲染的内容:
这是我从 TripsListScreen
导航时所期望的(创建新行程):
请帮忙!!!
最佳答案
MainMap.js 中的 ComponentDidMount 不会被触发,因为屏幕已经安装。请看这个`componentDidMount()` function is not called after navigation
关于javascript - 如何清理 React Native 中类组件的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60888082/