reactjs - npmアップデート後にReactのステートレスコンポーネントが壊れた
4か月ぶりにプログラミングに戻ってきたので、このプロジェクトを npm update することにしましたが、すべてのステートレス関数が壊れてしまいました。
interface INotFoundPageContainerProps {
history: any;
}
class NotFoundPageContainer extends React.Component<INotFoundPageContainerProps, any> {
constructor(props: INotFoundPageContainerProps) {
super(props);
this.onClickHomeButton = this.onClickHomeButton.bind(this);
}
onClickHomeButton(): void {
this.props.history.push('/');
}
render() {
return (
<NotFoundPage
onClickHomeButton={this.onClickHomeButton}
/>
);
}
}
export default withRouter(NotFoundPageContainer);
エラー:
TSは上記のコードの最後の行でエラーを出します:
TS2345: Argument of type 'typeof NotFoundPageContainer' is not assignable to parameter of type 'ComponentType<RouteComponentProps<any, StaticContext, any>>'.
Type 'typeof NotFoundPageContainer' is not assignable to type 'StatelessComponent<RouteComponentProps<any, StaticContext, any>>'.
Type 'typeof NotFoundPageContainer' provides no match for the signature '(props: RouteComponentProps<any, StaticContext, any> & { children?: ReactNode; }, context?: any): ReactElement<any>'.
回答 #1
React.Component のプロパティの型が正しくありません。なぜなら、あなたはそれを withRouter HOC でラップしているからです。
コンポーネント <NotFoundPageContainer/> は withRouter によってラップされており、ルーター特有のプロパティが渡されますが、NotFoundPageContainer の型定義にはそれが反映されていません。
その代わりにそのようなものを考えてみてください
import { RouteComponentProps } from 'react-router-dom';
interface INotFoundPageContainerRouterProps {
history: any;
}
interface INotFoundPageContainerProps
extends RouteComponentProps<INotFoundPageContainerRouterProps> {
}
そして、その後であなたはコンポーネントの型を正しく定義する準備が整います
class NotFoundPageContainer
extends React.Component<INotFoundPageContainerProps, any> { ... }
