簡體   English   中英

如何對數組中的隨機元素編號?

[英]How to number shuffled elements in array?

在我的應用程序中,我將特定視圖的順序隨機化。 但是,我在顯示正確的視圖序列號時遇到問題。

因此,第一個視圖的編號應為1,第二個視圖的編號應為2,依此類推。由於它們在數組中被混洗,所以我不知道如何事先訪問視圖的訂單號。 然后應該將正確的數字作為道具傳遞給特定的視圖組件以進行顯示。

 shuffle(arr) {
    var i, j, temp;
    for (i = arr.length - 1; i > 0; i--) {
      j = Math.floor(Math.random() * (i + 1));
      temp = arr[i];
      arr[i] = arr[j];
      arr[j] = temp;
    }
    return arr;
  };

 constructor() {
      const componentArray = [<Tasks incrementSequenceCounter={this.incrementSequenceCounter} count={this.state.count} />, <APM incrementSequenceCounter={this.incrementSequenceCounter} count={this.state.count} />, <ICAA incrementSequenceCounter={this.incrementSequenceCounter} count={this.state.count} />]

      const shuffledArray = this.shuffle(componentArray);

      this.state.shuffledArray = shuffledArray;
    }

組件應該以某種方式知道它在數組中的索引,但是我不知道從哪里開始。

改組之前,應將數組的元素包裝在一個對象中:

const componentArray = [
  {
    index: 0,
    component: <MyComponent />
  }

];

您可以使用簡單的map()從數組中創建它:

const indexArray = componentArray.map((el, i) => ({ index: i, component: el });

然后,您可以安全地改組indexArray

首先,我不喜歡在構造函數中初始化組件的想法。 這基本上使它們成為靜態的,但這可能就是您所追求的。 這是我的嘗試:

constructor() {
      const componentArray = [ 
          {
             type: Tasks, 
             props: { 
                 incrementSequenceCounter: this.incrementSequenceCounter,  
                 count: this.state.count 
               }
          }, 
          {
             type: APM, 
             props: { 
                 incrementSequenceCounter: this.incrementSequenceCounter,  
                 count: this.state.count 
               }
          },
          {
             type: ICAA, 
             props: { 
                 incrementSequenceCounter: this.incrementSequenceCounter,  
                 count: this.state.count 
               }
          }


      const shuffledArray = this.shuffle(componentArray);

      this.state.shuffledArray = shuffledArray.map(
            (componentConstructor, index) => React.createElement(componentConstructor.type, { ...componentConstructor.props, index })
     );
}

基本思想是在確定順序后構造它們。 這里的明顯缺點是,由於這是在構造函數中發生的,因此父組件中的任何狀態更改都不會反映在這些子組件中。 如果您不希望這樣做,則應在render和/或componentDidMount / Update中移動它

注意:基於其他答案,我需要澄清一下, 在我的理解中 ,問題是如何在將組件改組為組件本身之后傳遞索引。 這與其他人的回答不同,因此,如果我理解不正確,請通知我

暫無
暫無

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

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