_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();
}
我得到了我需要转换为react hooks代码的这段代码,除了这个focuslistener和componentwillunmount之外,我几乎了解了所有与useEffect()相关的东西,而且我在componentdidmount中得到了相同的代码,但是我想我知道如何做那个
答案 0 :(得分:1)
您应将代码替换为以下内容, 这里的loadItems函数从您的服务或后端加载项目,此函数将从焦点效果以及刷新中调用。
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 />;
}
此代码未经测试,因为它需要您的功能,但可以使您有所了解。