我有一段代码在Reactinative目前运行在应用程序启动。在类组件构造函数中。它使用React导航状态检查一系列条件,然后导航到某个地方。
class MyComponent<Props> {
constructor(props: Props) {
super(props);
// Some initialization code
}
}
我将其重构为使用useEffect
和useLayoutEffect
的钩子,但是现在的代码运行似乎只发生在初始呈现之后,导致导航发生前另一个屏幕的闪烁。
function MyComponent() {
useEffect(() => {
// Do some stuff
}, []);
return null;
}
是否与在函数组件中呈现之前运行的类构造函数等效?
发布于 2021-06-19 12:39:03
啊,我想出了一个解决办法。
以前,我是这样写代码的:
function MyComponent() {
useEffect(() => {
// Do some stuff
}, []);
return null;
}
结果是,等效的只是在函数本身中运行代码,因为它在实际的呈现到屏幕之前运行。
function MyComponent() {
const initializedRef = useRef(false);
if (!initializedRef.current) {
initializedRef.current = true;
// Do some stuff
}
return null;
}
这似乎与我以前的运行构造函数代码一样快。
https://stackoverflow.com/questions/68050183
复制相似问题