问题
I have a screen that it's title should set from AsyncStorage
and many screens are navigating to this screen (so I don't want pass the title everywhere I'm navigating).
As navigationOptions
is static
I'm not able to use this.state
and also can't set it's title by reading from AsyncStorage
(because AsyncStorage
is Async :)
How can I change the title inside the screen itself in such a situation?
回答1:
You can use setParams navigation action to set the title after async function ends.
Example
class SomeScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
const { params } = navigation.state;
return {
title: params ? params.screenTitle: 'Default Screen Title',
}
};
componentDidMount() {
AsyncStorage.getItem('someValueToGet').then((value) => {
this.props.navigation.setParams({screenTitle: value})
});
}
// OR You can wait for the someValueToGet
async componentDidMount() {
const value = await AsyncStorage.getItem('someValueToGet');
this.props.navigation.setParams({screenTitle: value})
}
/* render function, etc */
}
来源:https://stackoverflow.com/questions/50084311/react-native-dynamic-reactnavigation-title