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

标签 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);
}

方法,一切正常...

最佳答案

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

From the official documentation:

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

关于typescript - 无法在 Redux + Typescript 连接组件中使用静态 getDerivedStateFromProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51193657/

相关文章:

typescript - 非规范化 Array<A> 和 Array<B> where 子句为真,将 B 设置为 A 的命名属性

javascript - TypeScript 中的数组与字符串声明

javascript - 为什么在使用 react redux 过滤时我的原始状态会发生变化

flexbox - React-native flex - View 元素不显示

typescript - 有没有办法通过检查函数来实现类型缩小?

Angular, typescript 变化检测输入文本

reactjs - 如何在 React Redux 中创建临时状态?

javascript - 更新对象数组中的单个对象键值 react redux 状态

reactjs - 我对传递给在容器内使用重新选择的选择器函数的参数感到困惑

javascript - React-Redux 中的倒计时功能