当我this.setState()
在它之前调用一个我知道是字符串的道具时,我遇到了一个流错误。如果我将setState()
调用移到使用道具的行之后,错误就会消失。我得到的错误是:
无效的
此类型与字符串的预期参数类型不兼容
不明确的
此类型与字符串的预期参数类型不兼容
这两个错误都发生在同一行代码上。
这是该组件的精简版本。见执行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
修复它:
this.fetch(nextProps.endpoint); // NO ERROR!
this.setState({ isFetching: true });
这只是 Flow 中的一个错误,还是我遗漏了什么?