无法在Redux + Typescript Connected组件内使用静态getDerivedStateFromProps

时间:2018-07-05 14:18:49

标签: typescript redux react-redux getderivedstatefromprops

我无法在连接到Redux的类组件内部使用static方法。 TypeScript报告

Argument of type 'typeof SAI' is not assignable to parameter of type 'ComponentType<IStateProps & IDispatchProps>'.
  Type 'typeof SAI' is not assignable to type 'StatelessComponent<IStateProps & IDispatchProps>'.
    Type 'typeof SAI' provides no match for the signature '(props: IStateProps & IDispatchProps & { children?: ReactNode; }, context?: any): ReactElement<any> | null'.

容器:

export interface IStateProps {
  saiList: ISaiList
}

const mapStateToProps = (state: IRootState) => ({
  saiList: SaiListSelector(state)
});

export interface IDispatchProps {
  getSai: () => Dispatch<AnyAction>;
  postSai: (saiList: ISaiList) => Dispatch<AnyAction>;
}

const mapDispatchToProps = (dispatch: Dispatch) => ({
  getSai: () => dispatch<any>(getSaiList()),
  postSai: (saiList: ISaiList) => dispatch<any>(postSaiList(saiList))
});

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

组成部分:

interface ISAIState {
  editActive: boolean;
  localSai: ISaiList;
  sortBy: string;
}

type ISaiProps = IStateProps & IDispatchProps;

export default class SAI extends React.Component<ISaiProps> {

  public state: ISAIState = {
    editActive: false,
    localSai: [...this.props.saiList],
    sortBy: 'default'
  };

  static getDerivedStateFromProps(props: ISaiProps, state: ISAIState) {
    window.console.log(props, state);
  }

这是@types/react-redux不是最新的问题吗?或者是我这方面的问题?当我注释掉

static getDerivedStateFromProps(props: ISaiProps, state: ISAIState) {
    window.console.log(props, state);
}

方法,一切正常...

1 个答案:

答案 0 :(得分:4)

这是因为getDerivedStateFromProps希望返回一个对象。

From the official documentation:

  

getDerivedStateFromProps在调用渲染之前被调用   初始安装和后续更新上的方法。这应该   返回一个对象以更新状态,或者返回null则不更新任何内容。