无法在 Redux + Typescript 连接组件中使用静态 getDerivedStateFromProps

ady*_*yry 2 typescript redux react-redux getderivedstatefromprops

我无法static在连接到 Redux 的类组件中使用方法。打字稿报告

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'.
Run Code Online (Sandbox Code Playgroud)

容器:

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);
Run Code Online (Sandbox Code Playgroud)

组成部分:

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);
  }
Run Code Online (Sandbox Code Playgroud)

@types/react-redux是不是最新的问题还是我这边的问题?当我注释掉

static getDerivedStateFromProps(props: ISaiProps, state: ISAIState) {
    window.console.log(props, state);
}
Run Code Online (Sandbox Code Playgroud)

方法,一切正常...

小智 6

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

来自官方文档:

getDerivedStateFromProps 在调用 render 方法之前调用,在初始安装和后续更新中都是如此。它应该返回一个对象来更新状态,或者返回 null 来不更新任何内容。