【发布时间】:2021-03-28 23:18:39
【问题描述】:
当我刷新页面时,useEffect 只渲染其中两个函数中的一个,当我更改路由时它可以正常工作。
我正在使用 redux 设置车辆的全局状态并在 useEffect 中调度 API
所以我随时都有可用的车辆。但是,第二个函数vchStatusNumbers 它应该返回根据其状态过滤的数组的长度,它只运行一次,当我将其状态添加为依赖项时,我得到一个无限循环!
我需要了解我应该如何处理它?
下面是组件
import React,{useEffect,useState} from "react";
import StatisticBanner from "./StatisticBanner";
import {getAllVehicles,fetchVehiclesReport } from "./vehiclesReducer";
import { useSelector, useDispatch } from "react-redux";
const Home= ()=> {
const {vehicles} = useSelector(getAllVehicles); // get the state
const [statusTotal, setStatusTotal] = useState({})
const dispatch = useDispatch(); // dispatch fn to reducers
useEffect(() => {
dispatch(fetchVehiclesReport());
vchStatusNumbers();
}, [dispatch]);
const vchStatusNumbers = () =>{
const status = {}
let availableLength = 0
let parkedLength = 0
let serviceLength = 0
vehicles.map(vch=>{
if(vch.status === 'available'){
++availableLength
status.available = availableLength
}
if(vch.status === 'parked'){
++parkedLength
status.parked = parkedLength
}
if(vch.status === 'service'){
++serviceLength
status.service = serviceLength
}
})
setStatusTotal (status)
}
return (
<>
<div style={{ margin: 20 }}>
<StatisticBanner key={"statics"} statusTotal={statusTotal} />
</div>
</>
);
}
export default Home
【问题讨论】:
标签: reactjs react-hooks use-effect