基本 redux-saga,取回未定义的数据

Basic redux-saga, getting back undefined data

所以我目前正在学习 Redux-Saga 并且需要一点帮助。

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

你的箭头函数使用大括号 { 所以没有隐含的 return。要么显式 return axios.get(顺便说一下,因为你是 return 承诺,所以不需要使用 async/await)或更改为 parens 以利用显式 return.

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

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

你需要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/Whosebug/63000691/rootSaga.test.ts
  63000691
    ✓ should pass (16 ms)

  console.log
    [ 1, 2, 3 ]

      at src/Whosebug/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