簡體   English   中英

如何從內部使用 promise 獲取值的反應掛鈎返回 function

[英]how to return a function from react hook which internally uses a promise to get the value

我是 React 新手,想創建一個反應鈎子,它返回一個 function ,這個 function 在內部使用 promise 來獲取實際值。 這是我的示例代碼 -

export const useMyCustomHook = () => {

    let transKey = "";
    const [value, setValue] = useState("");
    const service = useContext(serviceContext);

    const getValue = (key: string) => {
        transKey = key
        return value
    }

    useEffect(() => {
        if (service) {
            service.GetValue(transKey).then((res: any) => {
                setValue(res);
            });
        }
    }, []);

    return getValue;
};

這是用法 -

const getValue = useMyCustomHook()

return (
    <div className="childComponent">
        <p>Page Title: {getValue('Key1')}</p>
        <p>Page Title: {getValue('Key2')}</p>
    </div>
)

每次通話我都得到相同的價值。

與其返回 function,不如直接返回一個值:

 export const getValue = (transKey) => { const [value, setValue] = useState(""); const service = useContext(serviceContext); useEffect( () => { service?.GetValue(transKey).then(setValue); }, // TODO: cleanup [service, transKey]); return value; }; // ----------------- return ( <div className="childComponent"> <p>Page Title: {getValue('Key1')}</p> <p>Page Title: {getValue('Key2')}</p> </div> )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM