我正在使用 react 和 redux 开发一个应用程序。我使用api。
申请流程:
第一个组成部分是您输入信息的表格(姓名、卡路里、饮食类型)。
class FormPage extends Component {
constructor(props) {
super(props);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.goToListOfMealPage = this.goToListOfMealPage.bind(this);
}
handleFormSubmit(data) {
const name = data.name;
const calories = data.caloreis;
const diet = data.diet;
const health = data.health;
console.log(name)
return loadData( name, calories, diet, health)()
.then(({ error }) => {
if (!error) {
setTimeout(this.goToListOfMealPage, 1500);
}
return error;
}
);
}
goToListOfMealPage() {
const { history } = this.props;
history.push('/ListMeal');
}
render() {
return (
<Form onSubmit={this.handleFormSubmit}/>
);
}
}
const mapDispatchToProps = (dispatch) => {
return {
loadData: () => dispatch(loadData())
}
};
FormPage = connect(mapDispatchToProps)(FormPage)
export default FormPage;
handleFromSubmit
功能是将表单数据发送到api链接(https://api.edamam.com/search?q= ${name}n&app_id=${key.id}&app_key=${key.key}&calories=${calories }&health=${health}&diet=${diet})。
填写表格并单击发送按钮后,我想在新的子页面上有一份膳食(食谱)列表。
这里loadData
是
const fetchDataStart = () => ({
type: actionTypes.FETCH_DATA_START,
});
const fetchDataSucces = (data) => ({
type: actionTypes.FETCH_DATA_SUCCESS,
data,
});
const fetchDataFail = () => ({
type: actionTypes.FETCH_DATA_FAIL,
});
const loadData = (name, calories, diet, health) => (dispatch) => {
dispatch(fetchDataStart());
return axios.get(`https://api.edamam.com/search?q=${name}n&app_id=${key.id}&app_key=${key.key}&calories=${calories}&health=${health}&diet=${diet}`)
.then(({ data }) => console.log(data) || dispatch(fetchDataSucces(data)))
.catch((err) => dispatch(fetchDataFail(err.response.data)));
};
发送表格后,我收到一个错误 TypeError: dispatch is not a function
我找不到这个错误的原因
您的代码存在一些问题:
this.props.loadData(params)
loadData()()
因为分派的动作不返回一个函数(尽管原始动作返回一个函数,但不要让它欺骗你)。因此,要使用loadData()
action,您需要将其映射到 props,如下所示:
const mapDispatchToProps = dispatch => ({
loadData: (name, calories, diet, health) => dispatch(loadData(name, calories, diet, health)),
});
然后像这样使用它:
componentDidMount() {
this.props.loadData(name, calories, diet, health)
.then(() => console.log('Success'))
.catch(err => throw new Error("Error", err.stack))
}
编辑:根据您新编辑的问题,redux 中的 connect 函数分别接受mapStateToProps
和mapDispatchToProps
,因此在您的代码中它应该是:
export default connect(null, mapDispatchToProps)(Component)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句