[英]Making requests to server with axios freezes React Native app
當用戶單擊按鈕時,我試圖從某個類別中獲取帖子,但是如果單擊兩次按鈕,則UI(交互元素,導航)將完全凍結幾秒鍾。
我試着刪除async / await並用promise做,結果相同。
const api = axios.create({
baseURL: 'http://192.168.1.33:5000/',
timeout: 3000,
});
// Action
export const getTrends = () => async (dispatch) => {
dispatch({
type: actions.REQUEST_TRENDS
});
const r = await api.post('getTrends');
const response = r.data;
return dispatch({
type: actions.RECEIVE_TRENDS,
articles: response.payload.data,
count: response.payload.count
});
};
// Button
<Button
vertical
active={tab === 'trends'}
onPress={() => {
this.setState({ tab: 'trends' });
this.reqTrends();
}}
>
<Icon name="md-trending-up" />
<Text>{i18n.t('TRENDING')}</Text>
</Button>
// reqTrends
async reqTrends() {
this.props.dispatch(getTrends());
}
預期結果:數據在后台加載,而用戶仍然可以與其他元素進行交互
實際結果:用戶必須等待請求完成才能使用其他任何東西
更改狀態始終是異步的。 設置狀態后,您可能無法嘗試通過以下操作繼續進行ajax調用:
onPress={() => {
this.setState({ tab: 'trends' }, () => this.reqTrends());
}}
這確保了處理流程不會重疊或導致內存泄漏。
另一個因素是您通常應將Async函數包裝在try / catch塊中。 該錯誤可能是在其自身的函數內部引起的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.