【问题标题】:Redux not updating a componentRedux 不更新组件
【发布时间】:2015-12-22 06:20:32
【问题描述】:

我有一个组件,它从 Redux 传递了一个“用户”属性,看起来像这样:

user: {
    user: {
        photos: []
    },
    userIsFetching: false,
    userIsFetchError: false
}

当“照片”更新时,React 不会重新渲染。我可以在 Redux 日志中看到“照片”确实得到了更新。这个问题是因为“照片”嵌套太深吗?

这是减速器:

function deleteUserPhoto(user, id) {
    return {
        ...user,
        photos: deletePhoto(user.photos, id)
    };
}

function deletePhoto(photos, id) {
    return photos.filter(photo =>
        photo.id !== id
    );
}

export function user(state, action) {

    if (typeof state === 'undefined') {
        state = {
            user: null,
            userIsFetching: false,
            userIsFetchError: false
        }
    }

    switch (action.type) {
        case USER_REQUEST:
            return {
                ...state,
                userIsFetching: true
            };
        case USER_RESPONSE:
            return {
                ...state,
                user: action.user
            };
        case USER_RESPONSE_ERROR:
            return {
                ...state,
                userIsFetching: false,
                userIsFetchError: true
            };
        case PHOTO_DELETE:
            return {
                ...state,
                user: deleteUserPhoto(state.user, action.id)
            };
        default:
            return state;
    }
}

谢谢。

【问题讨论】:

  • 你很可能用别的东西覆盖了user 属性。
  • 同意。虽然我无法立即找出问题所在,但要正确设置嵌套对象可能会很棘手,并且可能有一些微妙的方法来改变你不应该改变的东西。您可以考虑使用 github.com/gaearon/normalizr 之类的东西来扁平化您的商店。另外,当响应返回时,您是否撤消了您的标志?
  • 这些标志用于原始用户获取。当我与页面交互时(例如触发 onClick),页面会更新为正确的照片。

标签: javascript reactjs redux


【解决方案1】:

在您的实际代码中可能不是这种情况,但从我在您的代码示例中可以看到:在deletePhoto 方法中,调用filter 应该抛出一个TypeError,因为photos 在您的初始状态下是未定义的。

只要返回一个新状态,深度嵌套的属性就完全没有问题。在某些时候它可能会变得很麻烦,但是像 ImmutableJS 这样的库可以帮助我们管理非常复杂的状态。 调用操作后视图未更新是常见问题,通常由状态突变引起:http://rackt.org/redux/docs/Troubleshooting.html

【讨论】:

    【解决方案2】:

    我的愚蠢错误。道具正在更新,但我正在检查状态(由道具初始化)并且我没有在道具更改时更新状态。我只使用状态是因为我正在使用的 dropzone mixin 需要它。

    【讨论】:

      猜你喜欢
      • 2016-06-30
      • 2021-10-23
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 2019-06-13
      • 2019-06-05
      • 2020-01-24
      • 1970-01-01
      相关资源
      最近更新 更多