【问题标题】:Basic redux-saga, getting back undefined data基本的 redux-saga,取回未定义的数据
【发布时间】:2020-11-10 00:25:32
【问题描述】:

所以我目前正在学习 Redux-Saga,需要一些帮助。

我已经收到了这个动作,watcherSaga 已经捕捉到它并将它发送给 workerSaga,它使用 axios.get 运行一个函数来接收数据。在函数中,我实际上可以 console.log 数据并返回它,但是当它返回到 saga 时,数据是未定义的。这是一些截图,如果您需要任何其他信息,请告诉我。

【问题讨论】:

  • 三个图像是: 1. 正在接收的动作,displayBlogs 正在运行并调用 getBlogsSaga。 2. getBlogsSaga 使用 axios.get 获取显示在控制台日志中的数据,并返回此数据。 3. 我的数据是未定义的,即使我已经返回了。

标签: redux axios action redux-saga


【解决方案1】:

您的箭头函数使用花括号{,因此没有隐式返回。要么显式返回axios.get(顺便说一句,由于您返回的是一个promise,因此无需使用async/await)或更改为parens 以利用显式返回。

const getBlogsSaga = async () => {
  return await axios.get(..
}

const getBlogsSaga = async () => (
  await axios.get(...
)

【讨论】:

    【解决方案2】:

    你需要return await axios.get(API_URL)

    例如

    rootSaga.js:

    import { call, put, takeEvery } from 'redux-saga/effects';
    import { getBlogsSaga } from './getBlogSaga';
    
    const BLOGS = {
      LOAD: 'BLOGS_LOAD',
    };
    
    function setBlogs(payload) {
      return {
        type: 'SET_BLOGS',
        payload,
      };
    }
    
    function* displayBlogs() {
      const data = yield call(getBlogsSaga);
      console.log(data);
      yield put(setBlogs(data));
    }
    
    function* rootSaga() {
      yield takeEvery(BLOGS.LOAD, displayBlogs);
    }
    
    export { rootSaga, displayBlogs };
    

    getBlogSaga.ts:

    const getBlogsSaga = async () => {
      return await Promise.resolve().then(() => {
        return [1, 2, 3];
      });
    };
    export { getBlogsSaga };
    

    rootSaga.test.ts:

    import { displayBlogs } from './rootSaga';
    import { runSaga } from 'redux-saga';
    
    describe('63000691', () => {
      it('should pass', async () => {
        const dispatched: any[] = [];
        await runSaga(
          {
            dispatch: (action) => dispatched.push(action),
            getState: () => ({}),
          },
          displayBlogs,
        ).toPromise();
      });
    });
    

    测试结果:

     PASS  src/stackoverflow/63000691/rootSaga.test.ts
      63000691
        ✓ should pass (16 ms)
    
      console.log
        [ 1, 2, 3 ]
    
          at src/stackoverflow/63000691/rootSaga.ts:17:11
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        2.235 s, estimated 3 s
    

    【讨论】:

      猜你喜欢
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多