我遇到了以下代码
const ERROR_MSG = 'ERROR_MSG'
function errorMsg(msg){
return { msg, type:ERROR_MSG }
}
export function register({user,pwd,type}){
return dispatch=>{
axios.post('/user/register', {user,pwd,type})
.then(res=>{
if(res.status!==200){
dispatch(errorMsg(res.data.msg))
}
})
}
}
它的调度接收一个函数作为参数,参数返回一些东西。我对此不太满意,为什么需要创建额外的功能?如果 errorMsg 是全局的,则有意义,否则它将具有冗余功能。
如果我使用箭头函数然后在回调中直接分派(dispatch) Action 对象是否可能?
dispatch(()=>{res.data.msg, type:ERROR_MSG})
最佳答案
你可以但要注意你的箭头函数没有返回任何东西:
dispatch(()=>{res.data.msg, type:ERROR_MSG})
要么使用显式返回:
dispatch(()=>{return {res.data.msg, type:ERROR_MSG}})
或者用一个表达式包裹起来:
dispatch(()=> ({res.data.msg, type:ERROR_MSG}))
或者直接传对象给dispatch:
dispatch({msg: res.data.msg, type:ERROR_MSG})
关于javascript - redux Action ,使用箭头函数分派(dispatch)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47593734/