调用`this.setState()`会中断componentWillReceiveProps中道具的流类型检查 [英] Calling `this.setState()` breaks flow type checking on a prop in componentWillReceiveProps
问题描述
我在调用this.setState()
之前就知道它是字符串,这时我在道具上遇到了流错误.如果将setState()
调用移到使用prop的行之后,则错误消失.我收到的错误是:
I am getting a flow error on a prop that I know is a string when I call this.setState()
right before it. If I move the setState()
call after the line that uses the prop, the error goes away. The error I'm getting is:
空
此类型与预期的字符串参数类型不兼容
This type is incompatible with the expected param type of string
未定义
此类型与预期的字符串参数类型不兼容
This type is incompatible with the expected param type of string
两个错误都发生在同一行代码上.
Both errors occur on the same line of code.
这是该组件的精简版本.请参见componentWillReceiveProps
的实现:
Here is a stripped down version of the component. See the implementation of componentWillReceiveProps
:
import React, { Component } from "react";
import apiRequest from "../../services/apiRequest";
type PropsT = {
endpoint: ?string,
};
export default class ApiLoader extends Component {
props: PropsT
static defaultProps = { endpoint: null }
state = { isFetching: true }
componentWillReceiveProps(nextProps: PropsT) {
if (!nextProps.endpoint) return;
this.setState({ isFetching: true });
this.fetch(nextProps.endpoint); // FLOW ERROR HERE
}
fetch(endpoint: string) {
apiRequest.get(endpoint)
.then(() => this.setState({ isFetching: false }));
}
render(): React.Element<*> {
return <div>Whatever.</div>;
}
}
只需切换componentWillReceiveProps
中最后两行的顺序即可解决此问题:
Simply switching the order of those final two lines in componentWillReceiveProps
fixes it:
this.fetch(nextProps.endpoint); // NO ERROR!
this.setState({ isFetching: true });
这仅仅是Flow中的错误,还是我缺少了什么?
Is this just a bug in Flow, or am I missing something?
推荐答案
This is due to a type refinement invalidation: https://flow.org/en/docs/lang/refinements/#toc-refinement-invalidations
将endpoint
拉入其自己的变量中,您应该会很好.
Pull out endpoint
into its own variable and you should be good to go.
这篇关于调用`this.setState()`会中断componentWillReceiveProps中道具的流类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!