根据服务响应更新 redux 状态
Updating redux state based on service response
我已经使用 createSlice 创建了一个动作和缩减器。
在其中一项操作中,我使用来自状态的集合来调用服务。我想根据服务的响应更新状态数据。
成功时我想更新 state.locations
,失败时我想更新 state.errorData
。
const ManageInventoriesState = createSlice({
name: "ManageInventoriesReducer",
initialState,
reducers: {
updateIventoryLocations: (state) => {
updateService(state.oprationsList).then((resp) => {
state.locations = resp.data;
}).catch((err) => {
state.errorData = err.data;
});
},
},
});
但是当我尝试这样做时,出现以下错误,
Can not perform 'set' on a proxy that has been revoked.
如何正确操作。
来自 UI 我只是在调度操作(UI 是 connected component)。
dispatch(updateIventoryLocations());
Simsons,即anti-pattern的减速器。 Reducers need to be Pure Functions 并且不应包含异步调用。
此外,您的减速器需要 return 更新后的状态,但尚未 returned。
您可以更新它:
减速器
updateIventoryLocations: (state, action) => ({ ...state, locations: action.payload })
并且您使用服务结果调用操作:
updateService(state.oprationsList).then((resp) => {
dispatch(updateIventoryLocations(resp.data));
});
我已经使用 createSlice 创建了一个动作和缩减器。
在其中一项操作中,我使用来自状态的集合来调用服务。我想根据服务的响应更新状态数据。
成功时我想更新 state.locations
,失败时我想更新 state.errorData
。
const ManageInventoriesState = createSlice({
name: "ManageInventoriesReducer",
initialState,
reducers: {
updateIventoryLocations: (state) => {
updateService(state.oprationsList).then((resp) => {
state.locations = resp.data;
}).catch((err) => {
state.errorData = err.data;
});
},
},
});
但是当我尝试这样做时,出现以下错误,
Can not perform 'set' on a proxy that has been revoked.
如何正确操作。
来自 UI 我只是在调度操作(UI 是 connected component)。
dispatch(updateIventoryLocations());
Simsons,即anti-pattern的减速器。 Reducers need to be Pure Functions 并且不应包含异步调用。
此外,您的减速器需要 return 更新后的状态,但尚未 returned。
您可以更新它:
减速器
updateIventoryLocations: (state, action) => ({ ...state, locations: action.payload })
并且您使用服务结果调用操作:
updateService(state.oprationsList).then((resp) => {
dispatch(updateIventoryLocations(resp.data));
});