Как использовать TypeScript с помощью Router, connect, React.Component и настраиваемые свойства? - программирование
Подтвердить что ты не робот

Как использовать TypeScript с помощью Router, connect, React.Component и настраиваемые свойства?

У меня есть React Component, который использует connect, withRouter и получает пользовательские свойства. Я пытаюсь преобразовать это в TypeScript, и мне интересно, правильно ли я это делаю. По крайней мере, сейчас у меня нет ошибок.

Это код, который показывает концепцию:

import * as React from 'react'
import { connect } from 'react-redux';
import { withRouter, RouteComponentProps } from 'react-router';

import { 
  fetchTestLists,
  newTestList,
  displayTestList,
} from '../../../actions/index';

interface StateProps {
  testList: any;    // todo: use the type of state.myList to have validation on it
}

interface DispatchProps {
  fetchTestLists: () => void;
  newTestList: () => void;
  displayTestList: (any) => void;   // todo: replace any with the actual type
}

interface Props {      // custom properties passed to component
  className: string;
}

type PropsType = StateProps & DispatchProps & Props;


class MyTest extends React.Component<PropsType & RouteComponentProps<{}>, {}> {
  constructor(props) {
    super(props);
    this.handleCellClick = this.handleCellClick.bind(this);
    this.newTestList = this.newTestList.bind(this);
  }

  componentDidMount() {
    this.props.fetchTestLists();
  }

  handleCellClick(row, column, event) {
    this.props.displayTestList(row);
  }

  newTestList(e) {
    this.props.newTestList()
  }

  render() {
    return (
      <div className={this.props.className}>
      </div>
    );
  }
}

const mapStateToProps = (state): StateProps => ({
  testList: state.myList,   // todo: define a type for the root state to have validation here
});

const dispatchToProps = {
  fetchTestLists,
  newTestList,
  displayTestList,
};

export default withRouter<Props & RouteComponentProps<{}>>(connect<StateProps, DispatchProps>(
  mapStateToProps,
  dispatchToProps,
)(MyTest) as any);

Компонент используется следующим образом: <MyTest className={"active"} />

Мне пришлось много экспериментировать, чтобы это заработало. Например:

1) Когда я пропускаю типы для withRouter, как это: export default withRouter(connect... Тогда я получаю TS2339: Property 'className' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<Pick<RouteComponentProps<any>, never>, C...'. Это как-то было предложено здесь: Реагировать на маршрутизатор в TypeScript- как на маршрутизатор, так и на собственный реквизит, хотя я не понимаю эту концепцию.

2) Если вас интересует последняя строка as any, это связано с https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18999, и я получаю эту ошибку без нее:

 TS2345: Argument of type 'ComponentClass<Pick<any, never>> & { WrappedComponent: ComponentType<any>; }' is not assignable to parameter of type 'ComponentType<Props & RouteComponentProps<{}>>'.
 Type 'ComponentClass<Pick<any, never>> & { WrappedComponent: ComponentType<any>; }' is not assignable to type 'StatelessComponent<Props & RouteComponentProps<{}>>'.
 Type 'ComponentClass<Pick<any, never>> & { WrappedComponent: ComponentType<any>; }' provides no match for the signature '(props: Props & RouteComponentProps<{}> & { children?: ReactNode; }, context?: any): ReactElement<any> | null'.

Так это правильный способ сделать это? Где вы видите проблемы? Я в основном использую все последние версии, вот фрагмент из моего package.json:

"react": "^16.2.0",
"redux": "^3.7.2",
"react-dom": "^16.2.0",
"react-redux": "^5.0.6",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
"react-router-redux": "^4.0.8",
...
"typescript": "^2.7.2",
"@types/react-redux": "^5.0.15",
"@types/react-router": "^4.0.22",
"@types/react-router-dom": "^4.2.4",
"@types/react": "^16.0.38",
"@types/react-dom": "^16.0.4",
4b9b3361

Ответ 1

Я пытаюсь переписать ваш пример и получаю следующий код:

import * as React from 'react';
import { connect } from 'react-redux';
import { RouteComponentProps, withRouter } from 'react-router';

import { 
  fetchTestLists,
  newTestList,
  displayTestList,
} from '../../../actions/index';
import { Dispatch, bindActionCreators, AnyAction } from 'redux';

interface IStateProps {
  testList: IListType;    // todo: use the type of state.myList to have validation on it
}

interface IDispatchProps {
  fetchTestLists: () => AnyAction;
  newTestList: () => AnyAction;
  displayTestList: (value: string) => AnyAction;   // todo: replace any with the actual type
}

interface IProps {      // custom properties passed to component
  className: string;
}

type PropsType = IStateProps & IDispatchProps & IProps;

class MyTestComponent extends React.Component<PropsType & RouteComponentProps<{}>, {}> {
  constructor(props: PropsType & RouteComponentProps<{}>) {
    super(props);
    this.handleCellClick = this.handleCellClick.bind(this);
    this.newTestList = this.newTestList.bind(this);
  }

  public componentDidMount() {
    this.props.fetchTestLists();
  }

  public handleCellClick(row, column, event) {
    this.props.displayTestList(row);
  }

  public newTestList(e) {
    this.props.newTestList();
  }

  public render(): JSX.Element {
    return (
      <div className={this.props.className}>
      </div>
    );
  }
}

export const MyTest = connect(
  (state: IAppState, ownProps: IProps) => ({
      testList: state.testList,
      ...ownProps,
  }),
  (dispatch: Dispatch) => bindActionCreators<AnyAction, Pick<IDispatchProps, keyof IDispatchProps>>(
    { displayTestList, fetchTestLists, newTestList },
    dispatch,
),
)(withRouter(MyTestComponent));

interface IListType {
  someProp: string;
}

interface IAppState {
  testList: IListType;
  differentList: IListType;
}

Я изменил экспорт по умолчанию, чтобы присвоить результат обернутого класса MyTestComponent с помощью connect и withRouter HOC в MyTest. Затем я импортирую компонент MyTest, как этот

import { MyTest } from './MyTest' 

Я добавил интерфейсы, чтобы описать все свойства, которые были переданы из родительского компонента, также использовать withRouter и подключаться по-другому (более читабельно для меня).

Надеюсь это будет полезно

Ответ 2

Я решил эту проблему, вынудив установку пакета @types/react-redux. Я только что обновился с 4.4.5 до 5.0.15.

Возможно, стоит запустить новую npm install --save @types/[email protected].