在构建期间反应,redux和打字稿错误

时间:2018-01-05 16:29:01

标签: javascript reactjs typescript redux react-redux

我很反应和减少,我跟着this tutorial, 在关于Making a container的部分,我收到错误(编译失败):

./src/containers/Hello.tsx
(24,61): error TS2345: Argument of type 'typeof Hello' is not assignable to parameter of type 'ComponentType<{ enthusiasmLevel: number; name: string; } & { onIncrement: () => IncrementEnthusia...'.
  Type 'typeof Hello' is not assignable to type 'StatelessComponent<{ enthusiasmLevel: number; name: string; } & { onIncrement: () => IncrementEnt...'.
    Type 'typeof Hello' provides no match for the signature '(props: { enthusiasmLevel: number; name: string; } & { onIncrement: () => IncrementEnthusiasm; onDecrement: () => DecrementEnthusiasm; } & { children?: ReactNode; }, context?: any): ReactElement<any> | null'.

因为我在这个阶段一步一步地遵循教程,所以我不确定如何解决这个错误。

Hello容器:

import Hello from '../components/Hello';
import * as actions from '../actions/';
import { StoreState } from '../types/index';
import { connect, Dispatch } from 'react-redux';

export function mapStateToProps({ enthusiasmLevel, languageName }: StoreState) {
  return {
    enthusiasmLevel,
    name: languageName,
  };
}

export function mapDispatchToProps(dispatch: Dispatch<actions.EnthusiasmAction>) {
  return {
    onIncrement: () => dispatch(actions.incrementEnthusiasm()),
    onDecrement: () => dispatch(actions.decrementEnthusiasm()),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Hello);

Hello组件:

import * as React from 'react';
import './Hello.css';

export interface Props {
  name: string;                   // required
  enthusiasmLevel?: number;       // optional (using ? after its name)
  onIncrement?: () => void;
  onDecrement?: () => void;
}

class Hello extends React.Component<Props, object> {
  render () {
    const { name, enthusiasmLevel = 1, onIncrement, onDecrement } = this.props;

    if (enthusiasmLevel <= 0) {
      throw new Error('You could be a little more enthusiastic.');
    }

    return(
      <div className="hello">
        <div className="greeting">
          Hello {name + getExclamationMarks(enthusiasmLevel)}
        </div>
        <div>
          <button onClick={onDecrement}>-</button>
          <button onClick={onIncrement}>+</button>
        </div>
      </div>
    );

  }
}

export default Hello;

function getExclamationMarks (n: number) {
   return Array(n + 1).join('!');
 }

1 个答案:

答案 0 :(得分:1)

错误表明连接函数在提供有状态组件时需要无状态组件 - 因为React.Component的第二个参数是对象

我建议你选择:

const Hello = ({
  name,
  enthusiasmLevel = 1,
  onIncrement,
  onDecrement
}: Props) => {
  if (enthusiasmLevel <= 0) {
    throw new Error('You could be a little more enthusiastic.');
  }
  return(
    <div className="hello">
      <div className="greeting">
        Hello {name + getExclamationMarks(enthusiasmLevel)}
      </div>
      <div>
        <button onClick={onDecrement}>-</button>
        <button onClick={onIncrement}>+</button>
      </div>
    </div>
  );
}