reactjs - 调度不是一个函数反应
问题描述
我正在使用 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=${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()
动作,您需要将其映射到道具,如下所示:
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)
推荐阅读
- r - 分组并计算(第一和第二)和(第一和第三)之间的天数发生在R中的id
- nginx - 未考虑 pagespeed_no_transform 属性
- java - 如何在 JBoss 7.0 EAP 服务器中配置 SSL/HTTPS?
- bash - 期望 Script scp 目录中的最新文件
- java - 为 char 数组定义哈希码方法的最佳方法
- flutter - 在不是其子项的 TabBar 上使用 AppBar 样式
- sql - 为什么sql server做嵌套循环
- sql-server - 与精确匹配相比,范围内的聚集索引查找速度慢(基数估计不准确)
- css - Angular 6,如何配置 CSS 设置以在所有组件上创建持久的背景颜色?
- c# - 带字符串的双块引号不起作用