在 useEffect
内部使用异步 Function
复制 useEffect (() => {
let isMounted = true ;
const fetchData = async () => {
const article = await API .fetchArticle (id);
if ( ! isMounted) {
// check isMounted for async action which may have side effect
setArticle (article);
}
};
fetchData () .then ();
return () => {
isMounted = false ;
};
} , [id]);
复制 useEffect (() => {
async function fetchData () {
// fetch your data
}
fetchData ()
return () => {
// unbind/off event
}
} , [])
在 useEffect
中使用 setInterval/setTimeout
, clearInterval/clearTimeout
,无需将 id 转换为 useState
复制 function Counter () {
const [ count , setCount ] = useState ( 0 );
useEffect (() => {
const id = setInterval (() => {
setCount (prevCount => prevCount + 1 );
} , 1000 );
return () => clearInterval (id);
} , []);
return < h1 >{count}</ h1 >;
}
使用 useReducer
解救 useEffect
无法去除的依赖
复制 useEffect (() => {
const id = setInterval (() => {
setCount (c => c + step);
} , 1000 );
return () => clearInterval (id);
} , [step]);
复制 const initialState = () => ({
count : 0 ,
step : 1 ,
});
const ACTIONS = {
INCREMENT : 'INCREMENT' ,
DECREMENT : 'DECREMENT' ,
};
const countReducer = ({count , step} , action) => {
const { INCREMENT , DECREMENT } = ACTIONS ;
switch ( action .type)
{
case INCREMENT :
return {
count : count + step ,
};
case DECREMENT :
return {
count : count - step ,
};
default :
return state;
}
};
const [ state , dispatch ] = useReducer (countReducer , initialState);
const { count , step } = state;
useEffect (() => {
const id = setInterval (() => {
dispatch ({type : ACTIONS . INCREMENT }); // Instead of setCount(c => c + step);
} , 1000 );
return () => clearInterval (id);
} , [dispatch]);
return (< div >< span >{count}</ span >< span >{step}</ span ></ div >);
复制 function Video () {
const { PLAYLIST_UPDATED } = EVENT_TYPES ;
useEffect (() => {
const updatedCallback = () => {
//...
};
event .on ( PLAYLIST_UPDATED , updatedCallback);
return () => {
event .off ( PLAYLIST_UPDATED , updatedCallback);
};
} , []);
return (< div >...</ div >)
}
// Line 166:5: React Hook useEffect has a missing dependency: 'PLAYLIST_UPDATED'. Either include it or remove the dependency array react-hooks/exhaustive-deps
复制 import event from 'Event' ;
const { PLAYLIST_UPDATED } = EVENT_TYPES ;
function Video () {
useEffect (() => {
const updatedCallback = () => {
//...
};
event .on ( PLAYLIST_UPDATED , updatedCallback);
return () => {
event .off ( PLAYLIST_UPDATED , updatedCallback);
};
} , []);
return (< div >...</ div >)
}