gpt4 book ai didi

javascript - React navigation didfocus 事件监听器在类组件和功能组件之间的工作方式不同

转载 作者:数据小太阳 更新时间:2023-10-29 05:37:11 24 4
gpt4 key购买 nike

当我转换到此屏幕时,它会执行一些 API 调用以获取最新数据。但是当我从另一个带有钩子(Hook)版本的导航堆栈转换时,它似乎不会触发 didFocus 事件来触发 api 调用,而它与类版本一起工作。

如何使 hooks 版本与 class 版本具有相同的行为?

这两个版本有什么区别?

类组件版本

class someScreen extends Component {
componentDidMount() {
const {
navigation,
} = this.props;

this.navFocusListener = navigation.addListener('didFocus', () => {
// do some API calls here
console.log("class version");
API_CALL();
});
}

componentWillUnmount() {
this.navFocusListener.remove();
}
}

控制台输出

transition from other navigation stack to this screen: class version

transition between screens in same stack: class version

Hook 版本

const someScreen = ({
navigation,
}) => {
useEffect(() => {
const navFocusListener = navigation.addListener('didFocus', () => {
// do some API calls here
API_CALL();
console.log('hooooks');
});

return () => {
navFocusListener.remove();
};
}, []);
}

控制台输出

transition from other navigation stack to this screen: nothing is shown in console

transition between screens in same stack: hooooks

顺便说一句,这是我找到的解决方法

const someScreen = ({
navigation,
}) => {
useEffect(() => {
const isFocused = navigation.isFocused();

// manually judge if the screen is focused
// if did, fire api call
if (isFocused) {
// do the same API calls here
API_CALL();
console.log('focused section');
}

const navFocusListener = navigation.addListener('didFocus', () => {
// do some API calls here
API_CALL();
console.log('listener section');
});

return () => {
navFocusListener.remove();
};
}, []);
}

控制台输出

transition from other navigation stack to this screen: focused section

transition between screens in same stack: listener section

最佳答案

我想我找到了不一致行为的根本原因。还有一个叫做 useLayoutEffect 的钩子(Hook)

useLayoutEffect The signature is identical to useEffect, but it fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint.

useLayoutEffect 会阻塞绘画,而 useEffect 不会。这证实并解释了我的猜测,即 didFocus 事件已经触发,但它没有触发监听器,因为它错过了时机

所以在我的例子中,我必须使用 useLayoutEffect 而不是 useEffect

引用:https://kentcdodds.com/blog/useeffect-vs-uselayouteffect https://reactjs.org/docs/hooks-reference.html#uselayouteffect

关于javascript - React navigation didfocus 事件监听器在类组件和功能组件之间的工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57467317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com