首页 > 解决方案 > 收益调用返回未定义

问题描述

任何人都可以帮助我的代码有什么问题。我试图从这样的 sagas 文件中的 API 获取数据。我尝试在读取函数中控制台记录 response.data 并获得数据(数组)。但是当它在生成器函数的变量(数据)中赋值时,它没有定义。

// sagas.js

const PATH = 'product';

const read = async (path) => {
   await request.get(path)
      .then(response => {
         console.log('response from read :', response.data)
         return response.data;
      })
      .catch(err => { throw err })
}

function* loadProduct() {
   try {
      const data = yield call(read, PATH);
      yield put(actions.loadProductSuccess(data));
   }
   catch (error) {
      console.log('what's the error :', error)
      yield put(actions.loadProductFail());
   }
}


export default function* rootSaga() {
   yield all([
      takeEvery('LOAD_PRODUCT', loadProduct)
   ]);
} 

标签: callredux-sagayield

解决方案


非常感谢,我的问题解决了。我忘记了花括号,我像这样更改我的代码:

const PATH = 'product';

const read = async (path) => 
   await request.get(path)
      .then(response => {
         console.log('response from read :', response.data)
         return response.data;
      })
      .catch(err => { throw err })

...

它工作正常!


推荐阅读