如何对数组中的随机元素进行编号



在我的应用程序中,我随机化了特定视图的顺序。但是,我在显示正确的视图序列号时遇到问题。

因此,第一个视图应该得到数字 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;
    }

不知何故,组件应该知道它在数组中的索引,但我不知道从哪里开始。

首先,我不喜欢在构造函数中初始化组件的想法。这基本上使它们成为静态的,但这可能是你所追求的。这是我的尝试:

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和/或组件DidMount/Update

注意:根据其他答案,我需要澄清一下,根据我的理解,问题是如何在洗牌到组件本身后传递组件最终的索引。这与其他人的回答不同,所以如果我理解错误,请告诉我

在洗牌之前,数组的元素应该包装在一个对象中:

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

您可以使用一个简单的map()从数组中创建它:

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

然后你可以安全地洗牌你的索引数组

最新更新