我的 React 组件中正在进行这种初始化:
export default class LoginForm extends Component {
state = { // (*)
flash: {
message: null,
style: null
} // initialiser for flash message: show nothing
}
showError(error_message: string) {
this.setState({
flash: {
message: error_message,
style: "danger"
})
}
不幸的是,flow 将 state
对象的 flash
属性的初始化视为类型声明,并在后续的 setState()
中> 它将 flash
属性值的新声明标记为类型不匹配(“字符串与 null 不兼容”)。
我如何告诉 Flow 这里实际发生了什么,从而避免它报告错误?
<小时/>(*) 注意:我最初错误地在这一行中使用了 :
而不是 =
...@DanPrince 纠正了这一点。
最佳答案
您是否想使用 class properties syntax相反?
export default class LoginForm extends Component {
state = {
flash: { message: null, style: null }
}
}
据我所知,用 :
指定类属性现在不是、也从来不是有效的语法。在这种情况下,我想说 Flow 将其视为类型声明是预期的行为。
如果您想创建一个类属性并为其提供类型签名,则需要结合使用这两种语法。
class LoginForm extends Component {
state
: { flash: { message: ?string, style: ?Object } }
= { flash: { message: null, style: null } };
}
或者在一般情况下:
class {
property:Type = Value;
}
关于javascript - 如何帮助流程处理 react 组件状态初始化器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42465433/