簡體   English   中英

強制組件使用新道具重新安裝

[英]Force component to remount with new props

我正在使用react-native@0.60.5react-native-router-flux@4.0.6 我試圖從selectItems組件跳回到newCollection ,這是一個表單。

我創建了一個組件,它呈現帶有復選框的項目列表。 當用戶點擊完成按鈕時,我使用setParams將所選項目作為道具傳遞 - 如下所示:

 // SelectItems.js
 this.props.navigation.setParams({
   rightTitle: 'Done',
   onRight: () =>
     Actions.jump('newCollection', {
       selectedItems: this.state.taggedItems,
     }),
 });

這很好用,當newCollection組件呈現時,我可以在我的表單中顯示來自this.props.selectedItems的選定項目列表。

當組件掛載時,我需要使用this.props.selectedItems調用動作創建者。

這是動作:

      // NewCollection.js

      // Map the items selected in the the `selectItems` component
      // and invoke an action

      var fetchTaggedItems = new Promise((resolve, reject) => {
        this.props.taggedItemsFetch(this.props.taggedItems.map(x => x.uid));
        resolve(this.props.matchingOutfits);
      });

      fetchTaggedItems.then(x => {
            console.log(x);
            alert('done!');
          });

現在,我的理解是組件在收到這些新道具時應該重新安裝,但不會。 componentDidMount中使用日志,我看到它只安裝在第一個條目上。

我試過上面的代碼:

  • 使用Actions.refresh()而不是Actions.jump() — 什么也沒有發生
  • 使用static onEnter()更新組件 state 並強制重新安裝 — 無法訪問this.state
  • render()中調用動作創建者——無限循環
  • 在 state 中設置 boolean 調用calledActionCreator標志以防止無限循環 - 不起作用 - 將this.propscomponentDidUpdate()中的prevProps進行比較 - 錯誤:超過最大更新深度

我開始認為這是 React Native Router Flux 的一個錯誤。

希望此代碼對您有所幫助,這是我項目的一部分,我需要強制更新道具更改,在此代碼中您可以觸發道具更改及其必須執行的操作。 注意:當您使用 setState 時,您的組件將呈現。 在這個生命周期中,如果一個 props 發生了變化,它會調用 setState 來重新渲染組件。

        if (this.props !== prevProps) {
            this.setState({
               // do somethings
            })
        }
    }

好的,經過大量挖掘和實驗,我找到了一個可行的解決方案(至少在表面上)。

開始:

// NewCollection.js
  static onEnter() {
    Actions.refresh({key: Math.random()});
  }

使用普通的Actions.refresh()重新安裝組件似乎沒有任何效果。 提供隨機密鑰作為道具似乎會強制更新。

我確信這不是最優雅的解決方案,但它現在似乎有效。

暫無
暫無

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

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