網站搜尋

reactjs - React Context 錯誤:類型 'Dispatch>' 無法指派給類型 '(arr1: string[], arr2: string[]) => void'


我正在嘗試在 React+TS 中創建一個 context,它接收兩個字串陣列並使用這些陣列更新物件的狀態。但我在 return 語句中的 setChoices 遇到了 title 拼寫錯誤,無法解決。你們能幫我嗎?

程式碼:

import { createContext, useState } from 'react';

type GiftsType = {
  choices: string[];
  links: string[];
  setChoices: (arr1: string[], arr2: string[]) => void;
};

export const GiftsContext = createContext<GiftsType>({
  choices: [],
  links: [],
  setChoices: (arr1, arr2): void => {},
});

export function GiftsProvider({ children }) {
  const [gifts, setGifts] = useState<GiftsType>({
    choices: [],
    links: [],
    setChoices: (arr1, arr2) => void {},
  });

  return <GiftsContext.Provider value={{ ...gifts, setGifts }}>{children}</GiftsContext.Provider>;
}

答案#1

將你的代碼改成這個:

type GiftsType = {
  choices: string[];
  links: string[];
  setChoices: (arr1: string[], arr2: string[]) => void;
  setGifts: React.Dispatch<React.SetStateAction<GiftsType>>
};

它會有效。

答案#2

你的問題在這裡:

export function GiftsProvider({ children }) {
  const [choices, setChoices] = useState<GiftsType>({
    choices: [],
    links: [],
    setChoices: (arr1: string[], arr2: string[]) => void {}, // change the name
  });

  return <GiftsContext.Provider value={{ ...choices, setChoices }}> {children}</GiftsContext.Provider>;
}

你正在使用與你的狀態設置函數相同的名稱,而且在你使用擴展運算子的值中,你將有兩個 setChoices,這是錯誤的。