内部侦听器函数内部使用effect始终保持相同

发布于 2025-02-13 15:57:25 字数 793 浏览 3 评论 0原文

我遇到了有关React应用程序的问题。我有一个处理mapbox map实例的CUSTOMMAP组件。至少从我的角度来看,代码的关键部分如下:

const CustomMap = (props) => {
   const location = useSelector((state) => state.routing.location);
   ...
   useEffect(() => {
      ... map init ...
      map.on('moveend', () => {
         console.log(location);
      });
   }, [];

   useEffect(() => {
      console.log(location);
   }, [list of dependencies]);
}

想法是在mapbox识别操作 moveend 变量(与mapbox无关),从redux开始,然后对其做点事。由于仅需要一个处理程序,因此我将其注册在第一个使用仅一次的中,但我期望每次move> move> moveend < /代码>是触发的。

这没有发生,我想知道为什么? 位置始终与页面加载上的相同。关于React/Redux的哪个概念我误会了?在第二使用中记录的位置始终是正确的(当前在redux中的一个),但是使用效果触发依赖关系更改。

谢谢你!

I'm stuck with an issue regarding React app. I have a CustomMap component that handles the mapbox Map instance. The key parts of the code, at least from my perspective are as follows:

const CustomMap = (props) => {
   const location = useSelector((state) => state.routing.location);
   ...
   useEffect(() => {
      ... map init ...
      map.on('moveend', () => {
         console.log(location);
      });
   }, [];

   useEffect(() => {
      console.log(location);
   }, [list of dependencies]);
}

The idea was to register a listener on mapbox recognized action moveend, get the custom location variable (unrelated to mapbox) at that moment from Redux and do something with it. Since only one handler is required, I registered it in the first useEffect that is called only once, but I expected the value location will be fetched every time moveend is triggered.

This is not happening and I wonder why? The location is always the same as it is on page load. Which concept about React/Redux did I get wrong? The location logged in the second useEffect will always be the correct one (one currently in Redux) but that useEffect triggers on dependency change.

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文