guz*_*ajj 5 javascript reactjs redux redux-thunk react-redux
我有下一个 React/Redux/Thunk 代码:
这是我对 API 的调用:
//api.js
export const categoriesFetchData = (page, parentOf) => {
return axios.get(
url +
'categories/' +
'?parent=' +
parentOf +
'&limit=10' +
'&offset=' +
(page - 1) * 10,
);
};
Run Code Online (Sandbox Code Playgroud)
这是我的动作(我假装从这个动作返回一个 axios 承诺):
//actions.js
export const subCategoriesFetchData = (page = 1, parentOf) => {
return dispatch => {
dispatch(oneCategoryLoading(true));
return api.categoriesFetchData(page, parentOf)
.then(response => {
dispatch(subCategoriesFetchDataSuccess(response.data.results));
dispatch(oneCategoryLoading(false));
})
.catch(error => {
console.log(error);
});
};
};
Run Code Online (Sandbox Code Playgroud)
在我的容器中:
const mapDispatchToProps = dispatch => {
return {
fetchOneCategory: slug => {
dispatch(fetchOneCategory(slug)).then(() => {
console.log('working');
});
},
};
};
Run Code Online (Sandbox Code Playgroud)
但我收到此错误:
未捕获的类型错误:无法读取未定义的属性“then”
有什么问题以及如何在容器中返回承诺?
谢谢你的帮助。
抱歉,我会回答我自己的问题:
我改变这个:
const mapDispatchToProps = dispatch => {
return {
fetchOneCategory: slug => {
dispatch(fetchOneCategory(slug)).then(() => {
console.log('working');
});
},
};
};
Run Code Online (Sandbox Code Playgroud)
到
const mapDispatchToProps = dispatch => {
return {
fetchOneCategory: slug => {
return dispatch(fetchOneCategory(slug))
},
};
};
Run Code Online (Sandbox Code Playgroud)
现在我可以这样做:
import React from 'react';
import { connect } from 'react-redux';
class MyComponent extends React.Component {
componentDidMount() {
this.props.fetchOneCategory()
.then( () => { console.log('it works'); })
.catch( () => { console.log('on error'); });
}
render() {
return ( <p>Whatever</p> );
}
}
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助!
| 归档时间: |
|
| 查看次数: |
4041 次 |
| 最近记录: |