首页 > 解决方案 > 在 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")
    });
  };

标签: react-native

解决方案


解决方案之一是使用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}));
  };

推荐阅读