【问题标题】:react native shuffle flat list array反应原生 shuffle 平面列表数组
【发布时间】:2020-06-21 15:09:53
【问题描述】:

我正在尝试添加一个按钮来随机播放数组,但是当页面加载时,平面列表会随机播放。

这里有数组:

  constructor(props) {
    super(props);
    this.state = {
      deck: [
        { id: Math.random(), text: "0" }, 
        { id: Math.random(), text: "1" }, 
        { id: Math.random(), text: "2" }, 
        { id: Math.random(), text: "3" }, 
        { id: Math.random(), text: "4" }, 
        { id: Math.random(), text: "5" }, 
        { id: Math.random(), text: "6" }, 
        { id: Math.random(), text: "7" }, 
        { id: Math.random(), text: "8" }, 
        { id: Math.random(), text: "9" }, 
      ],
    };
  }

现在是随机播放功能

  shuffleDeck = (array) => {
    let i = array.length - 1;
    for (; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      const temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
    return array;
  };

随机播放按钮

          <TouchableOpacity style={styles.btn}>
            <Text
              style={styles.btnText}
              onPress={this.shuffleDeck(this.state.deck)}
            >
              Shuffle
            </Text>
          </TouchableOpacity>

最后是平面列表

        <View>
          <FlatList
            data={this.state.deck}
            numColumns={4}
            renderItem={({ item }) => (
              <View style={styles.gridCard}>
                <Text style={styles.gridCardTxt}>{item.text}</Text>
              </View>
            )}
          />
        </View>

我只想在按下按钮时随机播放,我错过了什么?


我现在可以加载未洗牌的屏幕,但现在按下洗牌按钮时无法更新数组;

下面的每个 cmets 是更新的代码

      <TouchableOpacity
        style={styles.btn}
        onPress={() => {
          this.setState({ deck: this.shuffleDeck(this.state.deck) });
        }}
      >
        <Text style={styles.btnText}>Shuffle</Text>
      </TouchableOpacity>

【问题讨论】:

  • 如果去掉 shuffle deck 方法会发生什么?
  • @evolutionxbox 哦,是的,我忘了提,数组按 0-9 的顺序显示
  • 您是否可以使用日志记录确保在加载时不会调用 shuffle 方法。
  • @evolutionxbox 是,但我不明白为什么
  • 如果您不使用属性而是将其用作实际方法会怎样?

标签: javascript react-native react-native-flatlist


【解决方案1】:

尝试将您的 onPress 更改为箭头功能:

onPress = {() => this.shuffleDeck(this.state.deck)}

【讨论】:

  • 就可以了。否则会立即调用该函数。
  • 谢谢。虽然它确实修复了,但我是否需要为列表添加更多代码以刷新或显示它是随机的?
  • @gSaenz 不确定您是否已经解决了这个问题。如果不是,我可以提供一个解释。为了真正改变你状态中的数据,你必须调用一个名为 setState 的 react 组件的方法。 setState 接受一个对象,然后将其与您之前的状态合并。在这里的反应文档中有更好的解释:reactjs.org/docs/state-and-lifecycle.html#using-state-correctly 离开这个,你必须调用 setState 来更新它。我会将您的 onPress 更改为: onPress = {() => { this.setState({ car​​ds : this.shuffleDeck(this.state.deck) }) }} -> 希望这会有所帮助
  • @NickD 啊,是的,我尝试使用setState,但在随机播放功能中。我知道这不是正确的地方,我也在 onPress 中尝试过,但仍然没有解决问题。 touchableOpacity 文档没有 setState,为什么我一开始没有尝试。另外,附注,我将 onPress shuffle 移动到可触摸的不透明度而不是 &lt;Text&gt;,我在上面更新以供参考。思考为什么仍然不起作用,如果需要,我可以打开新问题。
  • 事实证明我在平面列表中也缺少 extraData={this.state} 道具。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-08
  • 2021-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
相关资源
最近更新 更多