【发布时间】:2019-03-19 10:03:27
【问题描述】:
我正在开发一个使用 react 和 redux 的应用程序。我使用 api。
申请流程:
- 填写表格,
- 点击发送按钮,
- 将数据从表单发送到 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=${健康}&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
我找不到这个错误的原因
【问题讨论】:
-
你能提供
mapDispatchToProps吗?loadData(name, calories, diet, health)()- 当前调度是undefined -
@BrianLe 我编辑了我的帖子。 const mapDispatchToProps = (dispatch) => { return { loadData: () => dispatch(loadData()) } };
标签: reactjs redux react-redux