我在反应中调用 api 时无法读取未定义的属性"然后"



我收到类型错误:在 react.js 和 redux 中调用 api 时无法读取未定义的属性 'then'。

我的组件确实挂载功能是 -

componentDidMount() {
window.scrollTo(0, 0);
var requestedId = this.props.match.params.id;
this.props.fetchCategoryJoblist(requestedId).then(() => {
this.setState({ loading: false });
});
}

我得到无法读取的属性,然后在这一行this.props.fetchCategoryJoblist(requestedId).then(())

我的组件安装函数 -

componentDidMount() {
window.scrollTo(0, 0);
var requestedId = this.props.match.params.id;
this.props.fetchCategoryJoblist(requestedId).then(() => {
this.setState({ loading: false });
});
}

我的操作.js文件 -

// 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)));
};
}

那么如何在组件中使用该方法呢?

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)));
};
}

也许问题就在这里

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)));
};
}

最新更新