【问题标题】:Unable to use static getDerivedStateFromProps inside Redux + Typescript Connected Component无法在 Redux + Typescript Connected Component 中使用静态 getDerivedStateFromProps
【发布时间】:2018-07-05 14:18:48
【问题描述】:

我无法在连接到 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);
}

方法,一切正常...

【问题讨论】:

  • 你能解决这个问题吗?如果是这样,请分享解决方案,我遇到了这个问题
  • 是的,一定要返回纯对象:)

标签: typescript redux react-redux getderivedstatefromprops


【解决方案1】:

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

From the official documentation:

getDerivedStateFromProps 在调用渲染之前被调用 方法,无论是在初始挂载上还是在后续更新上。它应该 返回一个对象来更新状态,或者 null 不更新任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-16
    • 2020-05-02
    • 1970-01-01
    • 2012-01-15
    • 2020-06-08
    • 2021-12-19
    • 1970-01-01
    • 2018-06-14
    相关资源
    最近更新 更多