第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 .map() 函數(shù)在 useEffect 內的嵌套 setState 中無法使用展開運算符

使用 .map() 函數(shù)在 useEffect 內的嵌套 setState 中無法使用展開運算符

元芳怎么了 2023-09-21 10:42:34
const [columns, setColumns] = useState({    Configured: {      progress: "Configured",      tasks: [],    },    Approved: {      progress: "Approved",      tasks: [],    },    AwaitingPO: {      progress: "Awaiting PO",      tasks: [],    },    InProduction: {      progress: "In-Production",      tasks: [],    },    Delivered: {      progress: "Delivered",      tasks: [],    },  });  const { loading, error, data } = useQuery(GET_CUSTOMERS);  useEffect(() => {    if (data) {      data.customer.map((item) => {        setColumns({          ...columns,          [item.progress]: {            ...columns[item.progress],            tasks: [              ...columns[item.progress].tasks, ///Spread operator not working here              item            ],          },        });      });    }  }, [data]);我正在嘗試將多個指定的對象添加item到我的tasks數(shù)組中。在我擁有的三項中,僅添加了一項。嵌套狀態(tài)似乎相當困難,我覺得我在useEffect地圖函數(shù)本身方面做了一些錯誤的事情。
查看完整描述

2 回答

?
HUH函數(shù)

TA貢獻1836條經驗 獲得超4個贊

您的效果缺少對columns陳舊的關閉columns的依賴性。

為了防止依賴性,您可以將回調傳遞給狀態(tài)設置器函數(shù)。您還以錯誤的方式使用 Array.prototype.map,您應該使用 Array.prototype.reduce:

useEffect(() => {

? setColumns((columns) =>

? ? data

? ? ? ? data.customer.reduce(

? ? ? ? ? (columns, item) => ({

? ? ? ? ? ? ...columns,

? ? ? ? ? ? [item.progress]: {

? ? ? ? ? ? ? ...columns[item.progress],

? ? ? ? ? ? ? tasks: [

? ? ? ? ? ? ? ? ...columns[item.progress].tasks,

? ? ? ? ? ? ? ? item,

? ? ? ? ? ? ? ],

? ? ? ? ? ? },

? ? ? ? ? }),

? ? ? ? ? columns

? ? ? ? )

? ? ? : columns

? );

}, [data]);


查看完整回答
反對 回復 2023-09-21
?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

因為 data 是一個 useEffect 對象,無法跟蹤其內部變化,因為比較是通過引用進行的

你可以這樣做

這是通過物體的長度進行比較的方法

React.useEffect(()=>{},[data.length])

或者,您也可以這樣做

React.useEffect(()=>{},[JSON.stringify(data)]

這樣你就把它變成一個字符串并且不根據(jù)引用進行比較


查看完整回答
反對 回復 2023-09-21
  • 2 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號