Redux-saga:axios 不起作用但 fetch() 起作用

Redux-saga: axios is not working but fetch() does

我一直在尝试使用 axios 通过 workerSaga 制作 yield call() 来获取数据。获取数据后我一直无法更新状态。

我看到 this 2018 年的教程使用了不同的机制。它使用 yield fetch().

我使用 axios 的方法:

export default function* rootSaga() {
    yield takeLatest('GET_NEWS', workerSaga);
}

function fetchNews(){
    return axios ({
        method: 'get',
        url: 'https://newsapi.org/v1/articles?source=cnn&apiKey=API_KEY'
    });
}

function* workerSaga() {
    try{
        const resp = yield call(fetchNews);
        const article = resp.articles;

        yield put({ type: 'NEWS_RECEIVED', news: article });
    }
    catch (error){
        yield put({ type: 'NEWS_FETCH_ERROR', error });
    }
}

这里似乎一切正常,数据被获取(在redux devtools中看到)但是状态更新失败,即状态仍然是null.

2018 年的另一种方法:

function* fetchNews() {
    const json=yield fetch('https://newsapi.org/v1/articles?source=cnn&apiKey=API_KEY')
        .then(response => response.json(), );

    yield put({ type: "NEWS_RECEIVED", json: json.articles, });
}

function* workerSaga()  {
    yield takeLatest('GET_NEWS', fetchNews)
}

export default function* rootSaga() {
    yield all([workerSaga(), ]);
}

它完美无缺。

之前的 axios 无法正常工作的原因可能是什么?

您已经在评论中找到了两个正确的解决方案,但他们没有解释为什么这些解决方案有效。

问题是 fetchaxios 的 return 值不同(这就是我喜欢打字稿的原因——你会注意到其中的区别)。

fetch 编辑的响应 return 有一个名为 .json() 的方法。您调用 res => res.json() 以获取响应的内容。

axois 编辑的响应 return 已经为您解析了 JSON(取决于您的配置)。内容存储在名为 data.

的响应的 属性 中

您目前正在尝试从响应对象中获取 .articles,但您需要从 .data 属性 中获取它。有两种方法可以做到这一点。

  1. 您可以修改 fetchNews 函数,使其 return 只是数据,正如@cbr
  2. 所建议的
function fetchNews(){
    return axios ({
        method: 'get',
        url: 'https://newsapi.org/v1/articles?source=cnn&apiKey=API_KEY'
    }).then( resp => resp.data );
}
  1. 您可以按照@Aleksey L 的建议修改您的 workerSaga 以从正确的路径访问文章。
      const resp = yield call(fetchNews);
      const article = resp.data.articles;