如何帮助流处理反应组件状态初始化器?

时间:2017-02-26 06:23:09

标签: javascript reactjs flowtype

我在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正在将flash对象的state属性的初始化视为类型声明,并在随后的setState()中标记新的值声明flash属性作为类型不匹配("字符串与null"不兼容)。

如何告诉流程这里实际发生了什么,从而避免报告错误?

(*)注意:我最初错误地在此行中:而不是= ... @DanPrince更正了。

2 个答案:

答案 0 :(得分:2)

您的意思是使用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;
}

答案 1 :(得分:0)

type for React.Component可以使用prop类型和状态类型进行参数化。

type LoginProps = {
    // props here
}
type LoginState = {
    flash: {
        message: ?string,
        style: ?string
    }
}

export default class LoginForm extends Component<LoginProps, LoginProps, LoginState> {
    state : LoginState = { flash: { message: null, style: null } }
    showError(error_message: string) {
        this.setState({
                flash: {
                    message: error_message,
                    style: "danger"
                }
        })
    }
}

这应该有助于Flow正确协调所有类型。