Reactjs Redux传奇:axios不工作,但fetch()工作
我一直试图通过workerSaga进行Reactjs Redux传奇:axios不工作,但fetch()工作,reactjs,axios,redux-saga,Reactjs,Axios,Redux Saga,我一直试图通过workerSaga进行yield call()来使用axios获取数据。在获取数据后,我始终无法更新状态 我看到2018年的教程使用了不同的机制。它使用yield fetch() 我使用axios的方法: export default function* rootSaga() { yield takeLatest('GET_NEWS', workerSaga); } function fetchNews(){ return axios ({ me
yield call()
来使用axios获取数据。在获取数据后,我始终无法更新状态
我看到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 one不工作的原因可能是什么?您在评论中已经得到了两个正确的解决方案,但他们没有解释为什么这些解决方案会工作 问题在于
fetch
和axios
的返回值是不同的(这就是为什么我喜欢typescript的原因——您会注意到这种差异)
fetch
返回的响应有一个名为.json()
的方法。调用res=>res.json()
获取响应的内容
axois
返回的响应已经为您解析了JSON(取决于您的配置)。内容存储在响应的一个名为data
的属性中
您当前正试图从响应对象获取.articles
,但需要从.data
属性获取。有两种方法可以做到这一点
fetchNews
函数,使其只返回@cbr建议的数据workerSaga
以从正确的路径访问文章如果您使用axios({…}),那么(res=>res.data)是否有效?没有。请帮我解释一下语法,我是个新手。下一篇const
const文章
不就是为了这个目的吗?我是说,在axios版本的fetchNews
中。const文章=resp.data.articles
将.data
关键字放在resp.data.articles
中,使其正常工作。顺便说一句,它是做什么的?console.log
你的resp
看看它是什么样子的<代码>数据只是对象上的一个属性,但它是axios放置所有数据的属性。resp
上的其他属性是关于请求本身的信息,如标题和配置。您将看到resp.data
包含您认为resp
将包含的值(articles
等)。
function fetchNews(){
return axios ({
method: 'get',
url: 'https://newsapi.org/v1/articles?source=cnn&apiKey=API_KEY'
}).then( resp => resp.data );
}
const resp = yield call(fetchNews);
const article = resp.data.articles;