簡體   English   中英

如何幫助流程處理組件狀態初始化程序?

[英]How to help flow handle react component state initialiser?

我的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"
                })
        }

不幸的是,流程將state對象的flash屬性的初始化視為類型聲明,並且在隨后的setState()中將flash屬性值的新聲明標記為類型不匹配(“字符串與null不兼容”)。

我如何才能告訴Flow這里實際發生的情況,從而避免報告錯誤?


(*)注意:我最初錯誤地在該行中使用了:而不是= ... @DanPrince更正了該問題。

您的意思是改為使用類屬性語法嗎?

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;
}

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正確協調所有類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM