强力键入react-redux与typescript

时间:2018-01-17 02:21:37

标签: javascript reactjs typescript redux react-redux

尝试输入反应组件的参数时出错。我想严格键入组件的道具和状态上的属性,但是当我使用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 个答案:

答案 0 :(得分:18)

使用泛型时,您的接口位置错误:

宣布您的React组件时:

class Comp extends Component<ICompProps, ICompState>

ICompPropsICompState分别是你的组件道具和内部状态。

使用连接时:

connect<IMapStateToProps, IMapDispatchToProps, ICompProps, IReduxState>

IMapStateToProps代表mapStateToProps()函数返回的内容。 IMapDispatchToProps代表mapDispatchToProps()函数返回的内容。 ICompProps表示您的React组件道具(与上面相同) IReduxState代表您应用的Redux状态

所以在您的特定示例中:

声明你的React组件时:

class SideMenu extends Component<ISideMenu, {}>

使用ISideMenu作为道具,使用{}(空状态)作为州,因为您不使用任何州。

使用连接时:

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

您可以使用ISideMenu作为React组件道具和mapStateToProps返回的对象。但在实践中,最好创建2个独立的接口。

在我的应用中,我通常无法输入mapStateToProps返回对象,所以我只是使用:

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

答案 1 :(得分:4)

希望你不介意我从上面的代码中删除一些反模式。请检查我添加的评论。我还添加了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);