【问题标题】:React-Redux and Utility classReact-Redux 和实用程序类
【发布时间】:2021-04-12 16:14:57
【问题描述】:

我正在尝试编写一个实用程序类,该类从 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)

【问题讨论】:

    标签: reactjs typescript redux react-redux


    【解决方案1】:

    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 在这里没有意义。我推荐一个实用钩子,这样你就可以使用 useSelectoruseDispatch 钩子通过 React 上下文访问当前的商店实例。

    可能是这样的:

    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() 方法?

    【讨论】:

    • 谢谢琳达 - 你对 toJS() 函数的看法是正确的。我一直在寻找一种将数据传递给实用程序的方法,因此感谢您的建议
    猜你喜欢
    • 2016-07-07
    • 2019-02-07
    • 2017-10-16
    • 2016-06-11
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    相关资源
    最近更新 更多