简体   繁体   中英

What's the equivalent of this pull to refresh function in react native hooks?

   _onRefresh = async () => {
    this.setState({isRefreshing: true});
    await ExpenseReportHistoryBusiness.GetInstance().getListExpenseReportRequest();
    this.setState({isRefreshing: false});
    this.forceUpdate();
    this.focusListener = this.props.navigation.addListener(
      'didFocus',
      async () => {
        this.setState({displayMessage: true});
        await ExpenseReportHistoryBusiness.GetInstance().getListExpenseReportRequest();
        this.forceUpdate();
      },
    );
  };

  componentWillUnmount() {
    this.focusListener.remove();
  }

i got this code that i need to convert into react hooks code, i know pretty much everything related to useEffect() except for this focuslistener and componentwillunmount thing, and i got the same code in componentdidmount, but i think i know how to do that one

You should replace the code with something like below, Here the loadItems function loads items from your service or backend this function will be called from the focus effect and also the refresh.

function Scree1({ navigation }) {
  const [displayMessage, setDisplayMessage] = React.useState(false);

  const loadItems = async () => {
    setDisplayMessage(true);
    await ExpenseReportHistoryBusiness.GetInstance().getListExpenseReportRequest();
    setDisplayMessage(false);
  };

  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', async () => {
      await loadItems();
    });

    // will replace the component will unmount
    return unsubscribe;
  }, [navigation]);

  return <View />;
}

This code is not tested as it requires your functions but will give you the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM