在navigationOption中获取状态值?

时间:2018-08-08 10:52:19

标签: react-native

我在state(currentLocation)中有一个值,我想将其保留在导航栏的右侧。我怎样才能做到这一点? navigationOptions中不允许使用this.state.currentLocation,并给出undefined不是对象(评估'_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")
    });
  };

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我不确定,因为我目前没有什么可测试的,但是您应该能够检索到这样的状态值:

import { store } from "./App"; // Where you create your redux store

const currentLocation = store.getState().currentLocation;