如何立即将屏幕上的asyncStorage值更改为抽屉?

时间:2018-09-06 07:28:47

标签: react-native

我将抽屉式导航和堆栈式导航结合在一起。我有AsyncStorage将一个值存储在屏幕中,并且此值在DrawerScreen中使用/显示。该值已存储,但不会立即显示在抽屉屏幕中。我必须关闭该应用程序,然后重新打开它才能看到抽屉中的值更改。将其存储在屏幕中后,如何立即在抽屉中更改该值

export default (DrawerNav = DrawerNavigator(
  {
    Main: {
      screen: StackNav
    }
  },
  {
    contentComponent: props => <DrawerScreen {...props} />
  }
));


const StackNav = StackNavigator(
  {
      SearchLocation: {
          screen: SearchLocation
        }
  },
  {
    initialRouteName: "SearchLocation"
  }
);

DrawerScreen.js

_getCurrentLocation = async () => {
    const getLocation = await AsyncStorage.getItem("changedLocation");
    this.setState({
      currentLocation: getLocation
    });
};

componentDidMount() {
    this._getCurrentLocation();
}

render() {
    return (
        <Text>
            {this.state.currentLocation != ""
              ? this.state.currentLocation
              : "Choose Location Manually"}
        </Text>
    )
}

SearchLocation.js

_currentLocationAsync = async item => {
    await AsyncStorage.setItem("changedLocation", item);
};

<TouchableOpacity onPress={() => this._currentLocationAsync(item.item.name)}>
    <Text>{item.item.name}</Text>
</TouchableOpacity>

1 个答案:

答案 0 :(得分:0)

您应将位置更新通知Drawer组件。有许多方法可以实现监听器。我会为此使用EventEmiter。 您可以深入了解here

流程就像在根组件中,我们有这个发射器对象。

import EventEmitter from 'events';

constructor(props) {
  super(props);
  this._emitter = new EventEmitter();
}

componentWillUnmount() {
  this._emitter.removeAllListeners();
}

现在,您可以将此发射器通过props传递给必须发出或监听事件的任何子组件

<ComponentA emitter={this._emitter} />
<ComponentB emitter={this._emitter} />

当组件A发生更改时,它只需调用

this.props.emitter.emit('eventName', arg);

在组件B上,我们必须设置侦听器,如下所示:

componentWillMount() {
  this.props.emitter.addListener('eventName', (arg) => {
    // this block of code executes when 'eventName' is emitted with argument 'arg'
  });
}