javascript - 为什么一些导入的 React-Native Redux 操作会多次更改值并触发 onEffects?

标签 javascript ios react-native asynchronous redux

这是我的设置:

//store/actions/user.js

export const discoverFollowingStatus = followsId => {
  return (dispatch, getState) => {
    const userId = getState().user.user.id;
    findFollowingFromTo(userId, followsId).then(following => {
      dispatch({
        type: UPDATE_FOLLOWING_STATUS,
        payload: {
          followsId,
          following: following !== null,
        },
      });
    });
  };
};

//component.js

import {
  discoverFollowingStatus,
} from '../store/actions/user';
...
useEffect(() => {
    discoverFollowingStatus(followedUserId);
    console.log(discoverFollowingStatus);
  }, [followedUserId, discoverFollowingStatus]);

控制台正在打印许多未组合在一起的函数: logs

最大的问题是屏幕不断地重新渲染,因为 useEffect 正在触发。为什么导入的常量会发生变化并触发它?

最佳答案

这里的问题是在 useEffect 结束时 [] 中有两个对象/值。如果您想继续观察这两个值,这应该可以解决问题。

import {
  discoverFollowingStatus,
} from '../store/actions/user';
...
useEffect(() => {
    if(followedUserId && discoverFollowingStatus){
    discoverFollowingStatus(followedUserId);
    console.log(discoverFollowingStatus);
    }
  }, [followedUserId, discoverFollowingStatus]);

这里注意discoverFollowingStatus只有在本次同时定义了discoverFollowingStatusfollowedUserId时才会被触发。

否则建议在documentation拆分您的 useEffect 以分离关注点。当 followedUserId 被定义并且可以安全地被 discoverFollowingStatus

使用时,您应该使用 useEffect 来设置状态

关于javascript - 为什么一些导入的 React-Native Redux 操作会多次更改值并触发 onEffects?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59815115/

相关文章:

javascript - 添加选择字段会停止迭代; knockout

ios - 在 Swift 中更改 UITabBarItem 上的 selectedImage

ios - .calendarsForEntityType(EKEntityType.Reminder) 不返回提醒列表列表

javascript - 如何使用 async wait 在 React 组件的渲染中运行异步函数?

react-native - 不变违规 : requireNativeComponent: "AIRMap" was not found in the UIManager. 没有修复?

javascript - 带有静态方法的 JS 类看不到静态 setter

javascript - ionic 切换检查属性

javascript - jquery 函数不会在第一次点击时工作

ios - 图像动画数组的延迟

android-studio - 运行 react-native run-android 时无法提取 textlayoutbuilder-1.0.0.aa