【发布时间】:2020-03-05 10:44:53
【问题描述】:
如果我在组件中调度 dispatch(fetchResources()); this,我会将这两个对象添加到 Redux 状态。当我再次调用该函数时,我希望响应中的两个新对象被添加到列表中。相反,它为响应创建了一个新数组。我如何确保它被添加到数组中,而不是每次都获得一个新数组。 (见图)
界面:
export interface Resource {
[key: string]: Object[]
}
export interface AddResourceInterface {
type: typeof ADD_RESOURCE;
payload: Resource;
}
export type ResourceTypes =
AddResourceInterface |
RemoveResourceInterface;
export type AppActions = ResourceTypes;
行动:
export const addResource = (resource: Resource): AppActions => ({
type: ADD_RESOURCE,
payload: resource
});
export const fetchResources: ActionCreator<ThunkAction<any, any, any, any>> = () => {
return async (dispatch: Dispatch) => {
await fetch('http://localhost:3000/authorization')
.then(res => res.json())
.then(data => {
dispatch(addResource(data))
})
.catch(err => {
console.log(err);
})
}
};
减速机:
const initialState: Resource[] = [];
const resourceReducer = (
state = initialState,
action: ResourceTypes
): Resource[] => {
switch (action.type) {
case "ADD_RESOURCE":
return [...state, action.payload];
default:
return state;
}
};
端点返回:
{
"https://google.com": {
"enters": "today",
"scopes": [
"cloud:user"
]
},
"https://youtube.com": {
"enters": "today",
"scopes": [
"cloud:user"
]
},
}
【问题讨论】:
标签: reactjs typescript redux react-redux