Skip to content

Instantly share code, notes, and snippets.

@teal-front
Last active January 27, 2022 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teal-front/7261c930e085cdbb566f4e5c2c099408 to your computer and use it in GitHub Desktop.
Save teal-front/7261c930e085cdbb566f4e5c2c099408 to your computer and use it in GitHub Desktop.
React hooks best use
// 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