有一个简单的代码,我用react redux调用api。但还有一件事。我会定期增加屏幕上显示的进度值。我使用useEffect。但当我增加进度时,api会返回调用。我只想调用一次api。
这是我的代码的一个例子
const Do = () => {
const [progress, setProgress] = useState(1);
const dispatch = useDispatch();
dispatch(myApiCall);
useEffect(() => {
const interval = setInterval(() => {
setProgress(progress => progress + 10);
}, 1500);
return () => clearInterval(interval);
}, [progress]);
return (
<ProgressBar
completed={progress}
/>
);
};
您只需要调用useEffect
中的API:
const Do = () => {
const [progress, setProgress] = useState(1);
const dispatch = useDispatch();
useEffect(() => {
dispatch(myApiCall);
}, [dispatch]);
useEffect(() => {
const interval = setInterval(() => {
setProgress((progress) => progress + 10);
}, 1500);
return () => clearInterval(interval);
}, []);
return <ProgressBar completed={progress} />;
};
您需要在组件DidMount等效useEffect
:内部调用您的api调用
const Do = () => {
const [progress, setProgress] = useState(1);
const dispatch = useDispatch();
useEffect(() => {
dispatch(myApiCall);
}, []);
useEffect(() => {
const interval = setInterval(() => {
setProgress(progress => progress + 10);
}, 1500);
return () => clearInterval(interval);
}, [progress]);
return (
<ProgressBar
completed={progress}
/>
);
};