使用typescript时方法React getDerivedStateFromProps问题
Method React getDerivedStateFromProps problem when using typescript
使用 tslint。
我们有以下代码:
export default class TableCell extends React.PureComponent<IProps, IState> {
static getDerivedStateFromProps(nextProps: IProps, prevState: IState) {
return nextProps.status !== prevState.status ? {
status: nextProps.status
} : null;
}
constructor(props: any){
super(props);
this.state = {
status: props.status
};
}
...
}
导致以下错误:
class 方法 'getDerivedStateFromProps' 必须标记为 'private'、'public' 或 'protected'
有什么问题?
欢迎来到 SO!您可以尝试将该方法显式标记为 public 吗?
export default class TableCell extends React.PureComponent<IProps, IState> {
public static getDerivedStateFromProps(nextProps: IProps, prevState: IState) {
return nextProps.status !== prevState.status ? {
status: nextProps.status
} : null;
}
constructor(props: any){
super(props);
this.state = {
status: props.status
};
}
}
这将让 TS 知道任何代码都可以从 class 外部调用静态方法。
使用 tslint。 我们有以下代码:
export default class TableCell extends React.PureComponent<IProps, IState> {
static getDerivedStateFromProps(nextProps: IProps, prevState: IState) {
return nextProps.status !== prevState.status ? {
status: nextProps.status
} : null;
}
constructor(props: any){
super(props);
this.state = {
status: props.status
};
}
...
}
导致以下错误: class 方法 'getDerivedStateFromProps' 必须标记为 'private'、'public' 或 'protected'
有什么问题?
欢迎来到 SO!您可以尝试将该方法显式标记为 public 吗?
export default class TableCell extends React.PureComponent<IProps, IState> {
public static getDerivedStateFromProps(nextProps: IProps, prevState: IState) {
return nextProps.status !== prevState.status ? {
status: nextProps.status
} : null;
}
constructor(props: any){
super(props);
this.state = {
status: props.status
};
}
}
这将让 TS 知道任何代码都可以从 class 外部调用静态方法。