问题
I am getting TypeError: Cannot read property 'then' of undefined when calling the api in react.js and redux.
my component did mount function is -
componentDidMount() {
window.scrollTo(0, 0);
var requestedId = this.props.match.params.id;
this.props.fetchCategoryJoblist(requestedId).then(() => {
this.setState({ loading: false });
});
}
I am getting can not read property of then at this line this.props.fetchCategoryJoblist(requestedId).then(())
My componentDidMount function -
componentDidMount() {
window.scrollTo(0, 0);
var requestedId = this.props.match.params.id;
this.props.fetchCategoryJoblist(requestedId).then(() => {
this.setState({ loading: false });
});
}
My action.js file -
// code to get job listing based on category
export function setCategoryJoblist(categoryjoblist) {
return {
type: SET_CATEGORY_JOBLIST,
categoryjoblist
};
}
export function fetchCategoryJoblist(requestedId) {
var apiUrl = `http://18.207.190.61:4000/getJobByCategory/${requestedId}`;
return dispatch => {
fetch(apiUrl)
.then(res => res.json())
.then(data => dispatch(setCategoryJoblist(data.Jobs)));
};
}
So how can I use then method in componentDidMount Method ?
回答1:
Your fetchCategoryJobList
export function fetchCategoryJoblist(requestedId) {
var apiUrl = `http://18.207.190.61:4000/getJobByCategory/${requestedId}`;
return dispatch => {
// see here
fetch(apiUrl)
.then(res => res.json())
.then(data => dispatch(setCategoryJoblist(data.Jobs)));
};
}
Maybe the problem is in here
export function fetchCategoryJoblist(requestedId) {
var apiUrl = `http://18.207.190.61:4000/getJobByCategory/${requestedId}`;
return dispatch => {
// you don't have return here, so your call to API is won't return a promise call CMIIW
return fetch(apiUrl)
.then(res => res.json())
.then(data => dispatch(setCategoryJoblist(data.Jobs)));
};
}
来源:https://stackoverflow.com/questions/57743929/i-am-getting-cannot-read-property-then-of-undefined-while-calling-the-api-in-r