首页 > 解决方案 > 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)

标签: reactjstypescriptreduxreact-redux

解决方案


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 上下文中的useSelectoranduseDispatch钩子访问当前的 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()方法?


推荐阅读