【发布时间】:2017-04-15 20:11:49
【问题描述】:
这是在使用 thunk 时编写动作的一种方式,这导致 reducer 非常简单。
getCurrentUserPicture(){
return (dispatch,getState) => {
dispatch({type: "isloading", isLoading: true}); // shows a loading dialog
dispatch({type: "errorMessage"}); // clear errorMessage
dispatch({type: "warningMessage"}); // clear warningMessage
const userId = getState().user.get("currentUser").id;
getUserPicture(userId) // get from backend
.then(picture => {
dispatch({type: "userPicture", picture});
dispatch({type: "isLoading", isLoading: false});
}
)
.catch(e=>{
dispatch({type: "errorMessage", e});
dispatch({type: "isLoading", isLoading: true});
}
)
}
}
使用减速器,包括:
export reducer(state = initialState, action = {}) {
switch(action.type) {
case "isLoading":
return state.set("isLoading", action.isLoading)
这是另一种方法,其中操作“更干净”但减速器更复杂:
getCurrentUserPicture(){
return (dispatch,getState) => {
dispatch({type: "gettingCurrentUserPicture", true});
const userId = getState().user.get("currentUser").id;
getUserPicture(userId)
.then(picture => {
dispatch({type: "retrievedCurrentUserPicture", picture});
}
)
.catch(e=>{
dispatch({type: "errorRetrievedCurrentUserPicture", e});
}
)
}
}
在上述操作的减速器中,您将拥有例如:
export reducer(state = initialState, action = {}) {
switch(action.type) {
case "gettingCurrentUserPicture":
return state.set("isLoading", true)
.delete("errorMessage")
.delete("warningMessage")
一种方法比另一种更好吗?
【问题讨论】:
-
无论如何,第二种方法似乎更常见。
-
这个问题的赏金怎么了?
标签: reactjs redux immutability redux-thunk