Last active
January 27, 2022 08:22
-
-
Save teal-front/7261c930e085cdbb566f4e5c2c099408 to your computer and use it in GitHub Desktop.
React hooks best use
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://devtrium.com/posts/async-functions-useeffect | |
/** | |
* 当依赖改变导致useEffect再次执行时,两次async函数的到达时间顺序并不能保证 | |
* 所以在cleanup函数里,去掉前一次请求的状态码,即使前一次请求后到达,也不能执行`setData(json)` | |
*/ | |
useEffect(() => { | |
// flag | |
let isSubscribed = true; | |
const fetchData = async () => { | |
const data = await fetch(`https://yourapi.com?param=${param}`); | |
const json = await response.json(); | |
// set state with the result if `isSubscribed` is true | |
if (isSubscribed) { | |
setData(json); | |
} | |
} | |
fetchData().catch(console.error); | |
// cancel any future `setData` | |
return () => isSubscribed = false; | |
}, [ | |
// when `param` change, page render again | |
param | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment