我是非常新的redux。我有两个动作。两者都从REST API中分别获取数据。
一个reducer提供数据以填充表格,另一个reducer提供填充下拉列表的数据。两者都没有连接。我需要在页面加载时调度这两个动作。
问题是当我逐个发送这些操作时,商店只获得一个reducer的数据。一个调度将数据添加到存储,当另一个调度执行时,先前的数据就消失了。
//Action creators
// API URL
const apiUrl = 'http://58c24640e8215412002f7d38.mockapi.io/api/act/activities';
// Sync Action
export const fetchActsSuccess = (acts) => {
return {
type: 'FETCH_ACTS_SUCCESS',
payload: acts
}
};
//Async Action
export const fetchActs = () => {
// Returns a dispatcher function
// that dispatches an action at a later time
return (dispatch) => {
// Returns a promise
return Axios.get(apiUrl)
.then(response => {
// Dispatch another action
// to consume data
dispatch(fetchActsSuccess(response.data));
})
.catch(error => {
throw(error);
});
};
};
// API URL
const addApiUrl = 'http://58c24640e8215412002f7d38.mockapi.io/api/act/names';
// Sync Action
export const fetchNamesSuccess = (names) => {
return {
type: 'FETCH_NAMES_SUCCESS',
payload: names
}
};
//Async Action
export const fetchNames = () => {
// Returns a dispatcher function
// that dispatches an action at a later time
return (dispatch) => {
// Returns a promise
return Axios.get(addApiUrl)
.then(response => {
// Dispatch another action
// to consume data
dispatch(fetchNamesSuccess(response.data))
})
.catch(error => {
throw(error);
});
};
};
//reducers
export default function(state = null, action) {
var names = [];
switch (action.type) {
case 'FETCH_NAMES_SUCCESS':
return Object.assign(
[],
state,
action.payload
)
break;
default:
return names
}
return state;
}
export default function(state = null, action) {
var acts = [];
switch (action.type) {
case 'ADD_ACT':
return [
...state,
action.payload
]
break;
case 'FETCH_ACTS_SUCCESS':
return Object.assign(
[],
state,
action.payload
)
break;
default:
return acts
}
return state;
}
const store = createStore(
allReducers,
applyMiddleware(thunk, promise, logger)
);
store.dispatch(actsActions.fetchActs());
store.dispatch(actsActions.fetchNames());//this removes previous data in store
答案 0 :(得分:2)
你应该在每个redurs :)中返回默认状态,如下所示。
export default function(state = [], action) {
switch (action.type) {
case 'FETCH_NAMES_SUCCESS':
return [
...state,
action.payload
];
default:
return state;
}
}