Axios 不向 rootSaga 返回数据

Axios not returning data to rootSaga

所以我正在学习 Redux Saga 并使用 Axios 进行 API 调用。即使你不知道 Redux Saga,但你知道 Axios,你仍然可以提供帮助!

这是我的 rootSaga 的代码,它获取我的操作并调用 getBlogsSaga。

import {takeEvery, call, put, select} from 'redux-saga/effects'
import {BLOGS} from '../store/actions/constants'
import {getBlogsSaga} from './getBlogsSaga'
import {setBlogs} from '../store/actions/blogActions'

function* displayBlogs() {
    const blogs = yield call(getBlogsSaga);
    console.log(yield call(getBlogsSaga))
    yield put(setBlogs(blogs))
}
//watcher saga
function* rootSaga() {
    yield takeEvery(BLOGS.LOAD, displayBlogs)
}

export default rootSaga;

这是 axios 调用,它在我 console.log 时执行 return 数据。

import axios from 'axios'
const API_URL = "http://localhost:3004/blogs/";

const getBlogsSaga = async () => {
    await axios
  .get(API_URL)
  .then(function (response) {
    const data = response.data;
    console.log(data)
    return data;
  })
  .catch(function (error) {
    console.log(error);
 });
}

export {getBlogsSaga}

最后,这里有一个 console.log 来说明我的意思。 rootSaga 请求数据但从未收到数据,即使 axios 成功传递了数据。

getBlogsSaga.js:11 (3) [{…}, {…}, {…}]
rootSaga.js:8 undefined

saga 的 call 实际上可以很好地处理 promises,所以让你的 axios 代码像这样应该可以正常工作。不需要让它在这里等待,你可以在生成器中完成等待的繁重工作

import axios from 'axios'
const API_URL = "http://localhost:3004/blogs/";

const getBlogsSaga = () => {
  return axios
  .get(API_URL)
  .then(function (response) {
    const data = response.data;
    console.log(data)
    return data;
  })
  .catch(function (error) {
    console.log(error);
 });
}

export {getBlogsSaga}

我在这里做了一个简单的poc :) https://jsfiddle.net/vqoktfwd/1/