網站搜尋

reactjs - 展開參數必須要麼具有元組類型,要麼被傳遞給剩餘參數 React


我有這段 Typescript 程式碼:

const [history, setHistory] = useState([Array(9).fill(null)]);
const newHistory = history.slice(0, currentStep + 1);

當我想要像這樣使用展開運算子來設定新的狀態時:

setHistory(...newHistory);

我有錯誤:

展開的參數必須要么有元組類型,要么被傳遞給剩餘參數。

有人可以幫助我,我該如何正確地輸入這個?

答案#1

簡單來說:

因為你直接使用展開運算子,你正在將多個參數傳遞給你的 useState 函數,但 useState 函數只接受單一參數。相反地,應該使用展開運算子來創建一個單一陣列,然後將其傳入。

const newObject = [...newHistory];
setHistory(newObject);

// or, even simpler: 
setHistory([...newHistory]);

// NOT the below - this is passing in multiple arguments.
setHistory(...newHistory);

答案#2

一般來說,你可以通過使用 apply 來避免這類錯誤

setHistory(...newHistory); //drops error

setHistory.apply(null, newHistory) //works

但在你的例子裡有個問題:你用 [[null, null, null...]] 初始化歷史紀錄,然後取得它,切片成 [[null, null, ...], ...],並試圖用 setHistory([null, null], null) 將它設回去。

看起來你只需要使用 setHistory(newHistory);

答案#3

這對我來說效果完美!

setHistory(...(newHistory as []));