使用async await与redux reducer

3
下面的代码有什么问题?我得到了“async是保留字”的错误,我已经为异步/等待配置了babel。
下面这段代码出现异步错误:“async”是一个保留字,请检查一下Babel是否已经正确地配置了异步/等待。
export async function getCredit(){
  return dispatch => {
    try {
      const creditInfo = await axios.get(`/credit`)
    } catch (err) {
      dispatch(errorMsg(err.data.msg))
    }

    if(creditInfo.result === 200 && res.data.status === 1) {
      dispatch({
        type: GET_CREDIT,
        payload: creditInfo.data
      })
    }
  }
} 

我甚至尝试了这个

export async getCredit() => dispatch => {
  try {
    const creditInfo = await axios.get(`/credit`)
  } catch (err) {
    dispatch(errorMsg(err.data.msg))
  }

  if(creditInfo.result === 200 && res.data.status === 1) {
    dispatch({
      type: GET_CREDIT,
      payload: creditInfo.data
    })
  }
}
1个回答

2

这是一个高阶函数(返回函数的函数),您应该在使用await的嵌套函数中添加async,而不是外部函数(仅返回函数)。

export function getCredit(){
  return async dispatch => {

我明白了,但是我能不能去掉“function”这个词,改用箭头函数呢? - Jamie Aden
你可以这样写,我仅是跟随你的第一个代码片段。将第一行替换为 export const getCredit = () => { - Roy Wang
1
你也可以将这两行代码缩短为 export const getCredit = () => async dispatch => { - Roy Wang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接