【问题标题】:Why are some imported React-Native Redux actions changing values and triggering onEffects multiple times?为什么某些导入的 React-Native Redux 操作会更改值并多次触发 onEffects?
【发布时间】:2020-01-19 22:47:25
【问题描述】:

这是我的设置:

// 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]);

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

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

【问题讨论】:

  • 好像followedUserIddiscoverFollowingStatus 更新了。所以它会触发discoverFollowingStatus

标签: javascript ios react-native asynchronous redux


【解决方案1】:

这里的问题是您在 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 设置状态

【讨论】:

  • 我的组件继续一遍又一遍地渲染。是否与该操作更改状态这一事实有关?
  • 如果您正在收听在您的状态下不断刷新的值,那么可以。在这种情况下,您也许可以查看 useMemo。
猜你喜欢
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-18
  • 2021-10-06
  • 1970-01-01
相关资源
最近更新 更多