Реагировать на собственный массив плоских списков в случайном порядке - PullRequest
0 голосов
/ 21 июня 2020

Я пытаюсь добавить кнопку для перетасовки массива, однако, когда страница загружается, плоский список перетасовывается.

Здесь у меня есть массив:

  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>

Я хочу перемешивать только при нажатии кнопки, что я отсутствует?

Теперь я могу загрузить экран с массивом без перемешивания, но теперь не могу обновить массив при нажатии кнопки перемешивания;

в комментариях ниже здесь обновлен код

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

1 Ответ

1 голос
/ 21 июня 2020

Попробуйте изменить onPress на стрелочную функцию:

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