【问题标题】:using async await with redux reducer将 async await 与 redux reducer 一起使用
【发布时间】:2018-10-07 22:03:14
【问题描述】:

下面的代码有什么问题?我得到 async is a reserved word 错误,我为 async/await 配置了 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
    })
  }
}

【问题讨论】:

    标签: reactjs ecmascript-6 redux async-await


    【解决方案1】:

    这是一个高阶函数(一个返回函数的函数),你应该将async添加到使用await的嵌套函数中,而不是外部函数(它只是返回一个函数)。

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

    【讨论】:

    • 我明白了,但我不能去掉function这个词并改用箭头函数吗?
    • 你可以,我只是按照你的第一个代码sn-p。将第一行替换为export const getCredit = () => {
    • 也可以将这两行缩短为export const getCredit = () => async dispatch => {
    猜你喜欢
    • 2017-11-05
    • 2019-04-15
    • 2014-06-19
    • 2018-01-14
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多