【发布时间】: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