好像有2個地方要做到這一點。
首先是您的異步操作創建者,當您獲得響應時,您可以過濾響應數據並將其傳遞給成功操作創建者函數,以便將過濾的數據傳遞給Reducer。最後你的狀態將被過濾的數據改變。
第二位是你的減速機。你可以在reducer中過濾action.data。沒有什麼不妥。過濾您的數據,使用過濾的數據返回您的新狀態。就我個人而言,我會在減速機中做到這一點。所以動作創建者只是傳遞響應,然後我可以在reducer中進行調試。兩種方式都是可能的。
例:
你想從GitHub獲取數據向用戶展示:
/*
CONSTANTS # just variables to refer in your actions or reducer
you want to change your state for 3 different points
1- Request started
2- Request ended with success, you have the data you requested
3- Request ended with failure, you have error message as response
*/
let
GET_GITHUB_INFO = 'GET_GITHUB_INFO', // for request started
GET_GITHUB_INFO_SUCCESS = 'GET_GITHUB_INFO_SUCCESS', // for request success
GET_GITHUB_INFO_FAIL = 'GET_GITHUB_INFO_FAIL' ; // for request fail
/*
REDUCER # the function called in Redux createStore when you
# dispatch action (look at the source code for createStore)
*/
let reducer = (state, action) => {
case GET_GITHUB_INFO : // when you dispatch action to start request
return {
loading : true, /* # we changed our redux state to let components know
# request started. Component can show spinner etc. */
loaded : false, /* # change loaded state if it has changed before, for
# for instance think about a second request */
error : false /* # change error state if it has changed before, just
# like loaded case above */
};
case GET_GITHUB_INFO_SUCCESS : /* # you dont manually dispatch action for this
# from component, instead you write the code
# which dispatches action for this in your
# async action creator function. more on this
# later */
return {
loading : false, /* # we changed our redux state to let components know
# request ended. Component can hide spinner etc. */
loaded : true, /* # change loaded state because we have no error, we got
# success from our promise, more on that later */
error : false /* # no error */
}
}
// actions
export function getGithubInfo() {
return {
type : GET_GITHUB_INFO
}
};
export function getGithubInfoSuccess(data) {
return {
type : GET_GITHUB_INFO_SUCCESS,
data
}
};
export function getGithubInfoFail(data) {
return {
type : GET_GITHUB_INFO_FAIL,
data
}
};
export function getGithubInfoAsync({view,id}){
// you ll only call this action from your component
return function(dispatch) {
dispatch(getGithubInfo());
axios.get(DATA_URL)
.then((response) => {
/* filter your response and pass to action creator function */
dispatch(getGithubInfoSuccess(response.data)); // { type :"",views : ...}
})
.catch((error) => {
return dispatch(getGithubInfoFail({
error : error['error_message']
}))
});
}
}
所以根據你說的話,我就真的只需要一個動作的創造者'FETCH_DATA'(例如),然後將其發送給reducer。然後,而不是有switch語句基於'action.type',它將基於'action.data'?我想我對我在哪裏通過將邏輯推入縮減器來跟蹤哪些「視圖」來排序數據感到困惑。 – Jose
您可以提出更多問題。當我有時間時,我會回答。希望這可以幫助。 – FurkanO
我打算髮佈一個單獨的問題,因爲它看起來像我有一個稍微不同的問題來解決。這很有幫助,謝謝。如果可能的話,我會發佈一個鏈接到我的新問題。 – Jose