簡體   English   中英

使用redux使用相同值更新狀態時組件未更新

[英]Component not updated when state updated with same values with redux

我的反應原生應用程序中有一個登錄流程。 當用戶輸入其憑據時,將調度一個操作來驗證它們,然后調度其他操作以便通過reducer修改狀態。

在我的組件中,我注冊以這種方式更改:

function mapStateToProps(state) {
  return { userConnected: state.user.connected }
}

export default connect(mapStateToProps)(LoginScreen)

當我收到帶有該功能的新道具時,我會執行操作:

async componentWillReceiveProps(newProps){
  if(newProps.userConnected){
    this.props.navigation.navigate("Home");
  }else{
    this.showWrongCredentials();
  }
}

用戶第一次輸入錯誤的憑據時,使用connected = false更新道具,因此它顯示錯誤的憑據消息。 如果用戶使用一些錯誤的憑據單擊另一次,則狀態會收到相同的值connected = false ,因此不會調用方法componentWillReceiveProps,並且我無法再次顯示錯誤的憑據消息。

我怎樣才能做到這一點 ? 每次狀態更新時,即使值相同,我也希望觸發方法componentWillReceiveProps

是的,這種行為是設計的。

來自react-redux doc

如果考慮性能,提高性能的最佳方法是跳過不必要的重新渲染,以便組件僅在數據實際更改時重新呈現

或者如果你喜歡來源

請注意,selectorFactory負責入站和出站道具的所有緩存/記憶。 如果沒有在選擇器調用之間記住結果,請不要直接使用connectAdvanced,否則Connect組件將在每個狀態或props更改時重新呈現

您提到用戶在輸入憑據時單擊。 我建議用戶點擊后更改商店的某些屬性。 因此,對於每次點擊,都將驗證憑據並打印消息。

在存儲憑證之后,將附加變量用於存儲,該變量將用作每次用戶點擊的標記。 它可以命名為credentialEnteredFlag並在每次用戶輸入憑據時設置為true 然后執行操作以從componentWillReceivePropscredentialEnteredFlag重置為false

componentWillReceiveProps看起來像

async componentWillReceiveProps(newProps){
    if(newProps.credentialEnteredFlag){
        this.props.resetCredentialEnteredFlag();

        if(newProps.userConnected){
            this.props.navigation.navigate("Home");
        }else{
            this.showWrongCredentials();
        }
    }
}

暫無
暫無

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

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