繁体   English   中英

Axios get 请求在 useEffect 清理后未正确执行

[英]Axios get request not performing correctly after useEffect cleanup

我正在编写一个 axios get call useEffect,只要用户从下拉菜单中选择一个选项,它就会被调用。 它在第一次我 select 每个选项时获取信息,但每当我 go 回到以前选择的选项时,它会执行清理,但不会再次传递或“获取”来自端点的信息,导致“ object is undefined" 当试图在 flatList 显示内部传递时。

需要说明的是,我在选项列表中使用“selectDrowdown”。

 useEffect(() =>{ const CancelToken = axios.CancelToken; const source = CancelToken.source(); getGames(source); return () =>{ source.cancel(); }; }, [selectedOpt]);

 const getGames = (source) => { const opt = getOpt(); axios.get(`${URL}${opt}`, { cancelToken: source.token }).then(function (response){ setSelectedResults(response.data.data); }).catch((err) =>{ if(axios.isCancel(err)){ console.log('successfully aborted'); } else{ alert(error.message) console.log('getGameTest', error); } }); };

 <View style={styles.nav}> <SelectDropdown buttonStyle={styles.dropdownButton} defaultButtonText={'---Select---'} data={"Games", "Publishers and Developers", "Reviews", "Platform"} onSelect={(selectedItem, index) => { console.log(selectedItem, index) setSelectedOpt(selectedItem) }} buttonTextAfterSelection={(selectedItem, index) => { return selectedItem }} rowTextForSelection={(item, index) => { return item }} /> </View>

1:取消令牌已从 axios 弃用,请尝试另一种方法检查此

2:使用 async/await 语法来获得更简洁的代码

3:你应该将event object传递给回调

 onSelect={(e)=>{ //mapping and etc... }}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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