我在一个操作中使用 axios 并尝试通过链接操作调用该操作。我将在这里展示我想要做的事情:
this.props.fetchOffers().then(() => {
this.props.filter(this.props.filterOption);
});
但我收到错误:无法读取未定义的属性“then”
。
我不明白的是,在这个函数的正下方,我有另一个操作,它正在执行完全相同的操作并且工作得很好。
this.props.sortOffers(value).then(() => {
this.props.filter(this.props.filterOption);
});
这是一个工作版本。
这是操作文件:
import axios from 'axios';
import { reset } from 'redux-form';
import { FETCH_OFFERS, SORT_OFFERS, FETCH_OFFER, GET_FILTER, PAYMENT_TYPE } from './types';
export function paginateOffers(indexPosition, numberOfItems) {
return (dispatch) => {
axios
.get('/API/offers/pagination', {
params: {
position: indexPosition,
number: numberOfItems,
},
})
.then((response) => {
dispatch({ type: FETCH_OFFERS, payload: response.data });
})
.catch((error) => {
console.error(error);
});
};
}
export function fetchOffers() {
return dispatch => {
axios
.get('/API/offers')
.then((response) => {
dispatch({ type: FETCH_OFFERS, payload: response.data });
})
.catch((err) => {
console.error(err);
});
};
}
export function fetchOffer(id) {
return (dispatch) => {
axios
.get(`/API/offers/${id}`)
.then((response) => {
dispatch({ type: FETCH_OFFER, payload: response.data.result });
})
.catch((err) => {
console.error(`ERROR: ${err}`);
});
};
}
export function sortOffers(params) {
const { price, title, category, type } = params;
return dispatch =>
axios
.get('/API/offers/sort', {
params: { price, title, category, type },
})
.then((response) => {
dispatch({
type: SORT_OFFERS,
payload: response.data,
sortOptions: params,
});
dispatch({
type: PAYMENT_TYPE,
payment: type,
});
dispatch(reset('sorter'));
})
.catch((err) => {
console.error(err);
});
}
export function getFilterOption(option) {
return (dispatch) => {
dispatch({
type: GET_FILTER,
option,
});
};
}
最佳答案
您没有在 fetchOffers
操作创建者中返回 promise 。请注意您声明粗箭头函数的方式之间的细微差别。
试试这个:
export function fetchOffers() {
return dispatch =>
axios
.get('/API/offers')
.then((response) => {
dispatch({ type: FETCH_OFFERS, payload: response.data });
})
.catch((err) => {
console.error(err);
});
}
关于reactjs - 无法使用 axios 读取未定义的属性 `.then` 并在操作中使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46288816/