自定义钩子 returns Promise 但在 useEffect 内部解析
Custom hook returns Promise but resolves inside useEffect
我正在尝试编写一个挂钩,它执行动态 import
和 returns 一个 Promise
,它在导入完成时解析。
这是我设想的用法:
await useAfterImport("@custom/path");
这是我的错误尝试:
const useAfterImport = (importPath:string) => {
return new Promise<void>((resolve) => {
useEffect(() => {
import(importPath).then(() => {
resolve();
});
}, [importPath]);
});
};
此尝试失败,因为 Rules of Hooks 已被违反:
React Hook "useEffect" cannot be called inside a callback. React Hooks
must be called in a React function component or a custom React Hook
function. eslintreact-hooks/rules-of-hooks
有没有一种方法可以在不使用回调参数的情况下编写这样的钩子?
我真的很想 return 一个 Promise
这样就可以 await
ed.
我认为 Promises 不是正确的方法:
Here's how I envision it's usage:
await useAfterCustomImport("@custom/path");
React 组件函数体的顶层 - 唯一可以使用钩子的地方 - 不能有 await
在它们里面 - 它们需要渲染 something立即(即使暂时是一个空片段)。
对于您想要做的事情,状态更有意义。您可以执行以下操作:
const useAfterCustomImport = (importPath: string) => {
const [imported, setImported] = useState(false);
useEffect(() => {
import(importPath)
.then(() => setImported(true))
// .catch(handleErrors); // don't forget this part
}, []);
return imported;
};
然后
const libImported = useAfterCustomImport('some-lib');
return !libImported ? null : (
<div>
// JSX that uses the library
</div>
);
这遵循您当前代码的当前逻辑,它似乎假设导入仅包含副作用,而不是解析为可用值。如果模块解析为可用值,返回 imported
和来自自定义挂钩的解析值将是一个微不足道的调整。
我正在尝试编写一个挂钩,它执行动态 import
和 returns 一个 Promise
,它在导入完成时解析。
这是我设想的用法:
await useAfterImport("@custom/path");
这是我的错误尝试:
const useAfterImport = (importPath:string) => {
return new Promise<void>((resolve) => {
useEffect(() => {
import(importPath).then(() => {
resolve();
});
}, [importPath]);
});
};
此尝试失败,因为 Rules of Hooks 已被违反:
React Hook "useEffect" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function. eslintreact-hooks/rules-of-hooks
有没有一种方法可以在不使用回调参数的情况下编写这样的钩子?
我真的很想 return 一个 Promise
这样就可以 await
ed.
我认为 Promises 不是正确的方法:
Here's how I envision it's usage:
await useAfterCustomImport("@custom/path");
React 组件函数体的顶层 - 唯一可以使用钩子的地方 - 不能有 await
在它们里面 - 它们需要渲染 something立即(即使暂时是一个空片段)。
对于您想要做的事情,状态更有意义。您可以执行以下操作:
const useAfterCustomImport = (importPath: string) => {
const [imported, setImported] = useState(false);
useEffect(() => {
import(importPath)
.then(() => setImported(true))
// .catch(handleErrors); // don't forget this part
}, []);
return imported;
};
然后
const libImported = useAfterCustomImport('some-lib');
return !libImported ? null : (
<div>
// JSX that uses the library
</div>
);
这遵循您当前代码的当前逻辑,它似乎假设导入仅包含副作用,而不是解析为可用值。如果模块解析为可用值,返回 imported
和来自自定义挂钩的解析值将是一个微不足道的调整。