【问题标题】:How to help flow handle react component state initialiser?如何帮助流程处理反应组件状态初始化程序?
【发布时间】:2017-07-16 20:48:36
【问题描述】:

我的 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 更正了这一点。

【问题讨论】:

    标签: javascript reactjs flowtype


    【解决方案1】:

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

    【讨论】:

    • 这正是我的意思(= 不是:)。但奇怪的是,这并不能解决问题。无论哪种方式,flow 都会抱怨 string 和 null 之间的不匹配!想一想,我完全不清楚为什么 flow 会建立连接:我不知道它是如何知道setState() 的参数与state = ... 中设置的对象相同/跨度>
    【解决方案2】:

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

    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 正确协调所有类型。

    【讨论】:

    • 令人着迷!我不知道getInitialState。你如何看待this answer,这似乎建议不要将 getInitialState 与 ES6 类一起使用?
    • 我通常不使用 ES6 类和 React,所以我不知道 getInitialState() 是否有任何陷阱。不过这绝对是合理的。
    猜你喜欢
    • 2021-08-25
    • 1970-01-01
    • 2019-08-11
    • 2020-04-04
    • 2021-12-17
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 2021-06-27
    相关资源
    最近更新 更多