繁体   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