问题描述
我正在从事一个去年开始的项目,开发人员不在我身边。他们写了这段代码:
import { put,takeLatest,all,call } from 'redux-saga/effects';
import { getUserByUsernameService } from '../../services/userServices';
import 'regenerator-runtime/runtime';
function* fetchUser() {
const response = yield call(getUserByUsernameService);
yield put({ type: 'FETCHED_USER',payload: response.data.user });
}
function* actionWatcher() {
yield takeLatest('FETCHING_USER',fetchUser);
}
export default function* rootSaga() {
yield all([actionWatcher()]);
}
getUserByUsernameService 代码:
import {
makeGetRequest,makePostRequest,makePutRequest,makeDeleteRequest,} from '../utils/reqUtils';
export const getUserByUsernameService = (params) => {
let headers = {
"Access-Control-Allow-Origin": "*"
};
makeGetRequest('/user',params,headers);
}
makeGetRequest 的代码:
import axios from 'axios';
export const makeGetRequest = (endpoint,params = {},headers) => {
const options = {
method: 'GET',headers: { ...headers },params: params,url: endpoint,};
return axiosInstance(options)
.then((resp) => resp.data)
.catch((e) => {
console.log(e);
throw e;
});
};
在运行时我得到 Cannot read property 'data' of undefined
对应的代码
yield put({ type: 'FETCHED_USER',payload: response.data.user });
怎么了?
解决方法
生成器 yield 返回一个对象,您可以使用 next
方法对其进行迭代。
我认为您应该使用 response.next().valute.data.user
。
我还认为,当您在 fetchUser
中使用生成器时,您不应该产生 call
API 方法的结果。
function* fetchUser() {
const response = call(getUserByUsernameService);
yield put({ type: 'FETCHED_USER',payload: response.next().value.data.user });
}
,
这是一个简单的错字——您忘记了 return
函数中的某些内容!您正在调用 getUserByUsernameService
但没有返回响应。你想要
makeGetRequest