Redux 不更新组件
Redux not updating a component
我有一个组件从 Redux 传递了一个 "user" 道具,看起来像这样:
user: {
user: {
photos: []
},
userIsFetching: false,
userIsFetchError: false
}
当"photos"更新时,React 不会重新渲染。我可以在 Redux 日志中看到 "photos" 确实得到了更新。这个问题是因为 "photos" 嵌套很深吗?
这是减速器:
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
我的愚蠢错误。道具正在更新,但我正在检查状态(由道具初始化)并且我没有在道具更改时更新状态。我只使用状态,因为我正在使用的 dropzone mixin 需要它。
我有一个组件从 Redux 传递了一个 "user" 道具,看起来像这样:
user: {
user: {
photos: []
},
userIsFetching: false,
userIsFetchError: false
}
当"photos"更新时,React 不会重新渲染。我可以在 Redux 日志中看到 "photos" 确实得到了更新。这个问题是因为 "photos" 嵌套很深吗?
这是减速器:
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
我的愚蠢错误。道具正在更新,但我正在检查状态(由道具初始化)并且我没有在道具更改时更新状态。我只使用状态,因为我正在使用的 dropzone mixin 需要它。