【问题标题】:Redux dispatch in useEffect causing infinite rerenderRedux dispatch in useEffect 导致无限重新渲染
【发布时间】:2022-01-03 01:07:47
【问题描述】:

我曾尝试搜索以前的类似问题,但许多答案建议将依赖数组传递给useEffect,我已经这样做了。

这基本上是一个用户的展示页面:

const Profile = ({ currentUser, profileOwner, getProfileInfo, isMine }) => {
  useEffect(() => {
    getProfileInfo();
  }, [profileOwner]);

  return (stuff)
}

这是它的容器:

const mapStateToProps = ({ session, users }, ownProps) => ({
  currentUser: users[session.id],
  profileOwner: users[ownProps.params.userId],
  isMine: session.id === parseInt(ownProps.params.userId),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  getProfileInfo: () => dispatch(getProfileInfo(ownProps.params.userId)),
});

这是我认为会导致重新渲染的操作:

export const getProfileInfo = (userId) => (dispatch) =>
  axios.get(`/api/users/${userId}`).then((res) => res.data)
    .then((user) => dispatch(receiveProfileOwner(user)));

如果我从依赖数组中取出profileOwner,则不再有无限循环,但如果我导航到其他用户的个人资料,它将不会获取用户数据。 据我所知,profileOwner 的值在第一次获取后根本不应该改变,所以我仍然很困惑为什么我会遇到这个问题。

【问题讨论】:

标签: reactjs react-redux react-hooks use-effect


【解决方案1】:

看起来使用profileOwner 作为依赖是错误的。组件已经接收到路由参数作为 props,所以我将 useEffect 更改为:

const Profile = ({ currentUser, profileOwner, getProfileInfo, isMine, params: { userId } }) => {
  useEffect(() => {
    getProfileInfo();
  }, [userId]);

这有点乱,我希望有比添加更多道具更好的方法来做到这一点,但它确实解决了问题。

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2021-02-23
    • 2022-01-22
    • 2021-09-14
    • 2020-09-26
    • 1970-01-01
    相关资源
    最近更新 更多