[英]React: call custom hook from useEffect or run code before component mounts
I'm a bit reluctant to even ask this but here goes...我什至有点不愿意问这个,但是这里......
I have a custom hook useScript based off this implementation but I want to call it from useEffect
so that it runs before the component mounts but according to the rules of hooks I know I can't do that.我有一个基于此实现的自定义钩子 useScript,但我想从
useEffect
调用它,以便它在组件安装之前运行,但根据钩子的规则,我知道我不能这样做。
The issue is that I want to delay rendering my component until the script has loaded but I have no way to set state without causing a 'Too many re-renders' Error.问题是我想延迟渲染我的组件,直到脚本加载,但我无法设置 state 而不会导致“重新渲染过多”错误。
Here are two options I have tried that do NOT work:这是我尝试过的两个不起作用的选项:
useEffect(() => {
// Cannot call another hook from inside useEffect
useScript('https://cdnjs.cloudflare.com/ajax/libs/typescript/3.9.7/typescript.min.js');
}, []);
and和
const myComponent = (scripts) => {
const [loaded, setLoaded] = useState(false);
scripts.forEach(script => {
useScript('https://cdnjs.cloudflare.com/ajax/libs/typescript/3.9.7/typescript.min.js');
});
// where can I call setLoaded ??
return (loaded && <div>some content</div>);
};
This should be simple;这应该很简单; What am I forgetting???
我忘了什么???
One approach is for a hook to return a function that executes some functionality.一种方法是让钩子返回执行某些功能的 function。
So instead of:所以而不是:
function useScript() {
const [isLoaded, setIsLoaded] = useState(false);
// load the script...
return [isLoaded]
}
You can do:你可以做:
function useLoadScript() {
const [isLoaded, setIsLoaded] = useState(false);
const loadScript = () => {
// load the script...
}
return [isLoaded, loadScript]
}
So that the functionality can be consumed within another hook:以便可以在另一个钩子中使用该功能:
function MyComponent(props) {
const [isLoaded, loadScript] = useLoadScript()
useEffect(() => {
loadScript()
// ...
}, [])
if (!isLoaded) {
return <p>Loading...</p>
}
return (
// ...
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.