首页 > 解决方案 > addlistener focus react native 仅适用于第二次刷新 react-native

问题描述

因此,当我从第二个屏幕返回时,我一直在尝试从屏幕中的 asyncStorage 重新加载内容,但它只会在我来回导航时刷新

这是我的代码

componentDidMount() {
        const {navigation} = this.props
        navigation.addListener('focus', () => {
           
            AsyncStorage.getItem('Servers').then((servers) => {
                servers = JSON.parse(servers);
                if (servers) {
                    return this.setState({servers:servers, loaded: true})

                }
                this.setState({servers: [], loaded: true});

            });
            
        });

    };

另外,我认为每次完成 setState 时都应该重新渲染,但由于某种原因它没有这样做

标签: react-nativeaddeventlistenersetstatereact-navigation-v5

解决方案


这是预期的行为...因为您只为焦点事件注册了一个侦听器...。直接在 componentDidMount 中执行 addListener 的回调...

componentDidMount() {
  const {navigation} = this.props;
  
  yourFocusHandler();
  this.unsubscribe = navigation.addListener('focus', yourFocusHandler);

};

componentWillUnmount() {
  this.unsubscribe();
}

推荐阅读