【问题标题】:Axios not returning data to rootSagaAxios 不向 rootSaga 返回数据
【发布时间】:2020-11-10 11:31:00
【问题描述】:

所以我正在学习 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 时会返回数据。

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

【问题讨论】:

  • 我有一种直觉,你没有在 getBlogsSaga axios 函数中返回任何值,如何像 return await axios 一样返回它......

标签: reactjs redux axios redux-saga


【解决方案1】:

saga 的call 实际上可以很好地处理承诺,所以让你的 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/

【讨论】:

  • 哇,我已经被这个问题困扰了一天。谢谢!所以我只需要从 axios 中删除 async/await 吗?因为它导致它没有及时将数据返回给 saga?
  • 基本上是 :) 很高兴它有帮助
猜你喜欢
  • 2020-07-07
  • 1970-01-01
  • 2018-08-05
  • 2021-11-17
  • 2018-10-11
  • 1970-01-01
  • 2019-12-16
  • 2020-04-22
  • 1970-01-01
相关资源
最近更新 更多