reactjs - React-Redux 和实用程序类
问题描述
我正在尝试编写一个实用程序类,该类从 Redux Action 中进行的 API 调用获取其数据。jobActions.getJobs()
或者只访问已写入 Redux 状态的数据this.props.jobList
但这是一个简单的类,没有传递任何道具。而且我无法访问类之外的 getJobs() 函数
错误:“类型‘typeof JobsUtil’上不存在属性‘props’。”
我怎样才能让它工作?
export class JobsUtil {
// get jobs from API
public static getJobs(): Array<IDropDownOptions> {
const jobsList = this.props.jobActions.getJobs()
return jobsList;
}
}
function mapStateToProps(state) {
return {
jobList: state.toJS().jobList
};
}
function mapDispatchToProps(dispatch) {
return {
jobActions: bindActionCreators<any, Dispatch>(jobActions, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(JobsUtil as any)
解决方案
connect
旨在与 React 组件交互。你不能参加connect
任何其他类型的课程。
Argument of type 'typeof JobsUtil' is not assignable to parameter of type 'ComponentType<never>'.
Type 'typeof JobsUtil' is not assignable to type 'ComponentClass<never, any>'.
Type 'JobsUtil' is missing the following properties from type 'Component<never, any, any>': context, setState, forceUpdate, render, and 3 more.
JobsUtil
当您作为参数传递时,Typescript 应该会给您上述错误。JobsUtil as any
你通过写一个断言“相信我,这是一个 React 组件”来抑制错误。但它不是一个 React 组件,所以你会遇到更进一步的问题。
您需要以某种方式将有关您的商店的信息传递给JobsUtil
班级,可能通过constructor
. 但最终我认为class
这里没有意义。我推荐一个实用钩子,这样你就可以通过 React 上下文中的useSelector
anduseDispatch
钩子访问当前的 store 实例。
也许是这样的:
export const useJobActions = () => {
const dispatch = useDispatch();
return bindActionCreators(jobActions, dispatch);
}
export const useGetJobs = () => {
const {getJobs} = useJobActions();
const jobsList = useSelector(state => state.jobList);
useEffect( () => {
if (! jobsList) {
getJobs();
}
}, [getJobs, jobsList]);
return jobsList;
}
另外,为什么你state
会有一个toJS()
方法?
推荐阅读
- c - sscanf 在目标地址中溢出
- spring-boot - Spring Webflux:WebClient处理Expect:100-继续
- excel-formula - 我如何搜索一个月中的任何一天。搜索 2 月 19 日仅给出 2019 年 2 月 1 日的结果
- geometry - 栅格化体育场形状
- yii - 在 yii1 项目中使用 Yii2
- reactjs - 如何实现Editable Material-Ui Chips?
- javascript - 我尝试使用 offsetHeight 和 clientHeight 理解 translateY 计算
- excel - 在多个工作表中选择范围
- python - 如何使用python重命名多个文件夹中的多个文件?
- javascript - Material UI+React 悬停在选项卡上将无法正确打开和关闭