[英]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.