Redux未更新组件

Redux not updating a component

本文关键字:组件 更新 Redux      更新时间:2023-09-26

我有一个组件,它从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;
    }
}

谢谢。

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

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

我犯了一个愚蠢的错误。道具正在更新,但我正在检查状态(由道具初始化),我没有在道具更改时更新状态。我之所以使用state,是因为我正在使用的dropzone mixin需要它。