react-native - 在 navigationOption 中获取状态值?
问题描述
我有一个状态值(currentLocation),我想将它保存在导航栏的右侧。我怎样才能做到这一点?在 navigationOptions 中不允许使用 this.state.currentLocation 并给出 undefined is not an object(evalating '_this4.state.currentLocation) 错误
constructor(props) {
super(props);
(this.state = {
currentLocation: null
});
this._getCurrentLocation();
}
static navigationOptions = ({ navigate, navigation }) => ({
title: 'Search',
headerRight: (
<View>
<Text>{this.state.currentLocation}</Text> //this can not be done, how to get the currentLocation value in the headerRight?
</View>
)
});
_getCurrentLocation = async () => {
this.setState({
currentLocation: await AsyncStorage.getItem("currentLocation")
});
};
解决方案
解决方案之一是使用setParams
.
componentDidMount () {
this._getCurrentLocation()
}
static navigationOptions = ({ navigate, navigation }) => ({
title: 'Search',
headerRight: (
<View>
<Text>{navigation.state.params && navigation.state.params.currentLocation}</Text>
</View>
)
});
_getCurrentLocation = async () => {
const currentLocation = await AsyncStorage.getItem("currentLocation")
this.setState({currentLocation}, () => this.props.navigation.setParams({currentLocation}));
};
推荐阅读
- react-native - ReactNative - 从 redux-form 获取值
- python - 获取 AttributeError:“系列”对象没有属性“to_html”?
- ios - 如何检查字符串是否已包含 Swift 中的字符
- vue.js - 基于三元运算符应用内联样式背景图像
- hyperledger-fabric - 如何使用 Hyperledger Composer 在 Hyperledger Fabric 中存储大文件
- python - 使用python进行3D曲线拟合
- mysql - 您在 PDO 中的 SQL 语法有错误
- date - 取消内联编辑后使用自定义格式化程序免费 jqGrid 恢复日期
- c++ - 如何创建可以重新创建的自定义需求
- python - Pygame 的 colliderect 没有注意到碰撞