我正在創建我的第一個自定義鉤子。我希望鉤子回傳鉤子deviceType中 a 的結果Promise。
鉤:
export default function useDeviceType() {
// Finds the user's device type and sets the
// screen orientation appropriately.
useEffect(() => {
getDeviceTypeAsync().then((deviceType) => {
const orientationPromise = setScreenOrientation(deviceType);
return deviceType
});
}, []);
}
鉤子的使用:
export default function DevelopmentScreen() {
const deviceType = useDeviceType();
console.log(deviceType)
return null;
}
安慰:
不明確的
我可能很難理解這個useEffect鉤子,但我相信它應該在這里完全運行一次。
回傳的專案是否仍然未定義,因為Promise尚未解決?如果是這樣,那么我如何才能使用deviceTypeinside setScreenOrientation?
當我console.log(deviceType)進入useEffect鉤子時,我得到了適當的回應:
2
在此先感謝您對理解這一點的幫助!
最終編輯:
export default function useDeviceToSetOrientation() {
const [orientation, setOrientation] = useState(null);
useEffect(() => {
getDeviceTypeAsync().then((type) => {
const orientationPromise = setScreenOrientation(type);
orientationPromise.then((data) => {
setOrientation(data);
})
});
}, []);
return orientation
};
export default function DevelopmentScreen() {
const orientation = useDeviceToSetOrientation();
console.log(orientation)
return null;
}
輸出(正確):
4
uj5u.com熱心網友回復:
export default function useDeviceType() {
const [deviceType, setDeviceType] = useState();
useEffect(() => {
getDeviceTypeAsync().then((type) => {
const orientationPromise = setScreenOrientation(type);
setDeviceType(type);
});
}, []);
return deviceType
}
這應該可以修復該行為,然后deviceType可以通過const deviceType = useDeviceType();.
您在這里似乎誤解的是如何從useEffect作業中回傳值。你可以在這里閱讀它,但我們實際上使用它來創建將在我們的組件卸載時運行的清理函式。
編輯:您還可以在React 的檔案中看到自定義鉤子應該如何回傳值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/365447.html
標籤:javascript 反应原生
下一篇:在提交按鈕上反應原生表單處理
