我有一个对象数组
const w=[ {widgetId: 13, widgetKey: "currentMonthAvgSalesOrders", widgetName: "Current month average sales and orders", title: "Current month average sales and orders", type: "card", …},
{widgetId: 12, widgetKey: "orderSalesCurrentFinancialYear", widgetName: "Sales and orders of current financial year", title: "Sales and orders of current financial year", type: "card", …},
{widgetId: 28, widgetKey: "currentMonthAvgSalesPerSectorPerDay", widgetName: "Current Month Average Sales per sector per day", title: "Current Month Average Sales per sector per day", type: "card", …},
{widgetId: 28, widgetKey: "currentMonthAvgSalesPerSectorPerDay", widgetName: "Current Month Average Sales per sector per day", title: "Current Month Average Sales per sector per day", type: "card", …}]
我将它存储在一个 setState 函数中,该函数最初是一个空数组,根据条件进行过滤。我正在使用 rest 运算符将数据存储在 setState 中,但它给我重复的数据,每次我调用 useEffect 时,这些数据都会不断累加钩子
我的 useState 钩子
const [dataCards,setDataCards]=useState([]);
useEffect(() => {
if(Object.keys(userWidgetDetails).length>0){
const {widgets}=userWidgetDetails;
let dataArray=widgets.filter(s=>s.type==='card')
setDataCards([...dataCards,...dataArray])
}
}, [userWidgetDetails,customizeWidget])
这个实现有什么问题?
你试过这个吗?
setDataCards(dataCards => [...dataCards, ...dataArray])
这将允许使用状态变量的当前值。