在我的 expo typescript 應用程式中,我在根組件中有一個函式:
const getCardType = (type = ECardType.WOOD) => {
setCardType(type);
};
并將其傳遞到我的第一個子組件中:
<Slider data={slideData} autoPlay={false} getCardType={getCardType} />
這是我傳遞函式的第一個子組件,它型別宣告:
readonly getCardType?: (type: ECardType) => void;
const Slider: React.FunctionComponent<ISliderProps> = ({
data,
autoPlay,
getCardType,
})
之后,我將它傳遞給第二個子組件:
<SliderCardItem cardItem={item} index={index} getCardType={getCardType} />
在這個SliderItem組件中,我使用了這個函式:
useEffect(() => {
getCardType(cardType);
}, [cardType]);
但是有一個 TS 錯誤: 無法呼叫子組件中可能“未定義”的物件
我在onPress() 中設定了下面的cardType
我只在這個組件中有這個錯誤
解決這個錯誤的想法?
uj5u.com熱心網友回復:
?如果需要,請洗掉型別宣告中的 。如果不需要,則必須先檢查它是否存在。
另一點,getCardType實際上也是該效果的依賴項,但通過查看它是安全的,忽略它(因為它只是包裝了一個 setState)呼叫。
不過,我不喜歡忽略東西。所以如果我是你,我可能會這樣寫:
// useCallback makes getCardType referentially identical between renders
const getCardType = useCallback((type = ECardType.WOOD) => {
setCardType(type);
// safe to ignore setCardType in the dependencies because it's a dispatcher
},[]);
// ... and in the child:
useEffect(() => {
getCardType(cardType);
}, [ getCardType, cardType ]);
老實說,我很想知道useEffect孩子身上發生了什么,因為它聞起來有點腥味。
uj5u.com熱心網友回復:
getCardType 可能未定義,如您在此處的型別中所述:
getCardType?: (type: ECardType) => void;
然后你試圖在不檢查它是否存在的情況下呼叫它:
useEffect(() => {
getCardType(cardType);
}, [cardType]);
因此,您需要執行該檢查:
useEffect(() => {
if (getCardType) getCardType(cardType);
}, [cardType]);
或使用可選鏈接:
useEffect(() => {
getCardType?.(cardType);
}, [cardType]);
如果它始終存在,那么您可以在您的型別中將其設為非可選:
getCardType: (type: ECardType) => void;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/316876.html
標籤:javascript 打字稿 反应原生 不明确的
上一篇:'(id:any,title:any,body:any,image:any)=>Element'型別的引數不可分配給型別引數
