[react native中每次都聚焦页面时调用componentWillMount

问题描述 投票:0回答:1

我想在每次聚焦页面时都调用componentWillMount。我使用react-redux和react-navigation。

[使用react-navigation,我使用import { withNavigationFocus } from 'react-navigation';来检测页面是否处于活动状态,但是当我调用componentDidMount时,大约有几秒钟我看到了旧视图。为此,我要在聚焦页面时调用componentWillMount而不是componentDidMount。

这是我的代码:

class HomeScreen extends React.Component {

    componentWillMount() {
       this.props._loading(true);
    }

    omponentDidMount() {

    const { navigation } = this.props;
    this.focusListener = navigation.addListener('didFocus', () => {

        this.setState({loading: 0});

        this.props._loading(true);

        Api.get('s?type=Featured')
        .then( response => {
          if (response.profiles){
            this.setState({featured_users: response.profiles, loading: this.state.loading + 1});
          }
        }).catch((error) => {
          console.log(error);
          this.props._loading(false);
        });

        Api.get('s?type=Top')
        .then( response => {
          if (response.profiles){
            this.setState({featured_top: response.profiles, loading: this.state.loading + 1});
          }
        }).catch((error) => {
          console.log(error);
          this.props._loading(false);
        });
     });

  }

  componentWillUnmount() {
    // Remove the event listener
    this.focusListener.remove();
  }

  render() {
    if (this.state.loading >= 4){
      this.props._loading(false);
    }
    return (
       ...
    );
  }
}

const mapStateToProps = (state) => ({
    user: state.reducerUser,
    loading: state.reducerGeneral
});

mapDispatchToProps = dispatch => {
  return {
    _loading: loading => {
      dispatch(actionLoading(loading));
    },
    updateUser: user => {
      dispatch(actionUser(user));
    },
  }
}


export default withNavigationFocus(connect(mapStateToProps, mapDispatchToProps)(HomeScreen));

react-native react-redux components react-navigation
1个回答
0
投票

您可以将其添加到componentWillMount内部,并将您在addListener中编写的内容添加到每次:

this.focusListener = this.props.navigation.addListener('didFocus', () => {
      // The screen is focused

      this.getData();
    });
© www.soinside.com 2019 - 2024. All rights reserved.