我正在尝试同时使用React
和Redux
来管理我的应用状态。我试图从我的动作(SprintActions
)中调用一个方法,但是我不断收到错误消息
TypeError: props.getAllSprints is not a function
您能告诉我我在做什么错吗?
我的主要组件是Sprint
组件,它导入了SprintActions
这是我的Sprint
组件。
import React, { useEffect } from "react";
import { getSprints } from "./sprintActions";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
export const Sprint = (props) => {
useEffect(() => {
props.getAllSprints();
}, []);
return (
<div style={{ zIndex: 1 }}>
{sprints &&
sprints.map((s) => (
<p>{s.id}</p>
))}
</div>
);
};
Sprint.propTypes = {
getAllSprints: PropTypes.func,
};
const mapStateToProps = (state) => ({
sprints: state.sprints,
});
const mapDispatchToProps = (dispatch) => ({
getAllSprints: bindActionCreators(getSprints, dispatch),
});
export default connect(mapStateToProps, mapDispatchToProps)(Sprint);
这是我的SprintActions
import * as types from "../constants/ActionTypes";
import Axios from "axios";
export const getSprints = () => {
console.log("get sprints");
return (dispatch) => {
Axios.get("http://127.0.0.1:5000/sprints").then((response) => {
const sprintData = response.data;
dispatch(getAllSprints(sprintData));
});
};
};
export const getAllSprints = (data) => ({
type: types.GET_SPRINTS,
data: data,
});
感谢您的时间和耐心。
您想要在这里实现的目标应该通过使用redux-thunk
(调度api请求)或redux-sagas
(稍微复杂一些的imo)来完成。您可以阅读this guide,这非常有帮助!
您的问题是您的getSprints
操作不会返回具有属性(类型,...有效负载)作为described here的对象。如果您使用getAllSprints动作,则会看到它会起作用。
也请检查the docs of redux for bindActionCreators
我希望这会有所帮助
bindActionCreators
用于将调度功能传递到您的商店不知道的组件中,因为您无论如何都在mapDispatchToProps
中使用connect
,因此根本不需要它(无论如何,实现它的方式都是错误的,欢迎查看https://redux.js.org/api/bindactioncreators以获取文档)。
只需使您的mapDispatch尽可能基本:
const mapDispatchToProps = (dispatch) => ({
getAllSprints: () => dispatch(getSprints()),
});