使用 typescript 强输入 react-redux 连接

IT技术 javascript reactjs typescript redux react-redux
2021-05-08 10:49:24

我在尝试为我的 React 组件键入参数时遇到错误。我想严格输入组件的 props 和 state 上的属性,但是当我使用 Redux 这样做时,当我将 mapStateToProps 传递给 connect 函数时出现错误。

这是组件代码:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import FileExplorer from '../components/file-explorer/file-explorer';
import { ISideMenu, ISideMenuState } from '../models/interfaces/side-menu';

    class SideMenu extends Component<ISideMenu, ISideMenuState> {
        render() {
            return (
                <div>
                    {this.props.fileExplorerInfo !== null &&
                        <FileExplorer fileExplorerDirectory={this.props.fileExplorerInfo.fileExplorerDirectory}/>
                    }
                </div>
            );
        }
    }

    const mapStateToProps = (state: ISideMenuState) => {
        return {
            fileExplorerInfo: state.fileExplorer
        };
    };

    export default connect<ISideMenu, null, ISideMenuState>(mapStateToProps)(SideMenu);

所以错误发生在这一行:

export default connect<ISideMenu, null, ISideMenuState>(mapStateToProps)(SideMenu);

当我将鼠标悬停在该行中的“mapStateToProps”一词上时,我看到了错误:

Argument of type '(state: ISideMenuState) => { fileExplorerInfo: FileDirectoryTree | null; }'
is not assignable to parameter of type 'MapStateToPropsParam<ISideMenu, ISideMenuState, {}>'.
  Type '(state: ISideMenuState) => { fileExplorerInfo: FileDirectoryTree | null; }' is not
assignable to type 'MapStateToProps<ISideMenu, ISideMenuState, {}>'.
    Types of parameters 'state' and 'state' are incompatible.
      Type '{}' is not
assignable to type 'ISideMenuState'.
        Property 'fileExplorer' is missing in type '{}'.

这些是我在 react 组件中使用的两个接口:

export interface ISideMenu {
    fileExplorerInfo: FileExplorerReducerState | null;
}

export interface ISideMenuState {
    fileExplorer: FileDirectoryTree | null;
}

对此错误的任何见解将不胜感激!

2个回答

使用泛型时,您将接口的位置弄错了:

当你声明你的 React 组件时:

class Comp extends Component<ICompProps, ICompState>

随着ICompPropsICompState分别为您的组件的props和内部状态。

使用连接时:

connect<IMapStateToProps, IMapDispatchToProps, ICompProps, IReduxState>

IMapStateToProps表示您的mapStateToProps()函数返回的内容IMapDispatchToProps表示您的mapDispatchToProps()函数返回的内容ICompProps代表你的 React 组件props(同上) IReduxState代表你的应用程序的 Redux 状态

所以在你的特定例子中:

当声明你的 React 组件时:

class SideMenu extends Component<ISideMenu, {}>

使用ISideMenu的props和{}(空状态)的状态,你不使用任何状态。

使用连接时:

connect<ISideMenu, {}, ISideMenu, ISideMenuState>(mapStateToProps)(SideMenu);

您可以ISideMenu将 React 组件 props 和mapStateToProps. 但在实践中,最好创建 2 个单独的接口。

在我的应用程序中,我通常不会打扰输入mapStateToProps返回对象,所以我只需使用:

connect<{}, {}, ISideMenu, ISideMenuState>(mapStateToProps)(SideMenu);

希望你不介意我从上面的代码中删除一些反模式。请检查我添加的评论。我还添加了 withRouter 来更好地说明模式

import * as React from "react";
import { bindActionCreators } from "redux";
import { withRouter, RouteComponentProps } from "react-router";
import { connect } from "react-redux";
import { compose } from "recompose";

// OUR ROOT REDUX STORE STATE TYPE
import { State } from "../redux"; 

import FileExplorer from "../components/file-explorer/file-explorer";

// interfaces starting with 'I' is an antipattern and really
// rarely needed to be in a separate file

// OwnProps - that's what external code knows about out container
type OwnProps = {};

// this comes from redux
type StateProps = {
  fileExplorer: FileDirectoryTree | null;
};

// resulting props - that what container expects to have
type Props = OwnProps & StateProps & RouteComponentProps<any>;

// no need to have a class, SFC will do the same job
const SideMenu: React.SFC<Props> = props => {
  return (
    <div>
      {this.props.fileExplorerInfo !== null && (
        <FileExplorer
          fileExplorerDirectory={
            this.props.fileExplorerInfo.fileExplorerDirectory
          }
        />
      )}
    </div>
  );
};

// compose (from recompose lib) because usually we have more than 1 hoc
// say let's add withRouter just for fun



export default compose<Props, OwnProps>(

  withRouter,

  // it's important to read the typings:
  // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-redux/index.d.ts
  connect<StateProps, {}, {}, State>(s => ({
    fileExplorerInfo: s.fileExplorer
  })),

)(SideMenu);