【发布时间】:2018-11-27 07:54:20
【问题描述】:
在我的 actionCreators 中,我在操作上调用了一些其他 API 端点,例如UPDATE_CART_ITEM等
一开始我是这样使用axios的return axios()...:
export const login = (username, password) => (dispatch) => {
dispatch(requestLogin())
const URL = `${USERS_URL}?username=${username}&password=${password}`
return axios(URL)
.then((response) => {
return response.data
})
.then((user) => {
dispatch(loginSuccess(user))
// save the user on localStorage
localStorage.setItem('user', JSON.stringify(user))
// direct the logedin user to the games page
history.push('/')
})
.catch(() => {
return dispatch(loginFailure())
})
}
现在我像这样使用 async/await:
// On payload i have the obj: {prId: 'xxxxx'}
export const updateCartItem = (payload) => async (dispatch) => {
const response = await fetch('cart/update',
{
body: JSON.stringif(payload),
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
method: 'POST',
})
// I m not sure if i have to return the result
const result = await response.json()
// I dispatch the action with the payload
await dispatch(return {
payload,
type: UPDATE_CART_ITEM,
})
} catch (err) {
dispatch(cartActionFail(err))
}
}
那么,在updateCartItem 函数内部,我应该如何处理result 呢?
由于我将payload传递给reducer,看来我不需要它。
【问题讨论】:
标签: javascript reactjs redux fetch state