反应本机随机播放平面列表数组
react native shuffle flat list array
我正在尝试添加一个按钮来随机排列数组,但是当加载页面时,平面列表会随机排列。
我这里有数组:
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>
尝试将您的 onPress 更改为箭头函数:
onPress = {() => this.shuffleDeck(this.state.deck)}
我正在尝试添加一个按钮来随机排列数组,但是当加载页面时,平面列表会随机排列。
我这里有数组:
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>
尝试将您的 onPress 更改为箭头函数:
onPress = {() => this.shuffleDeck(this.state.deck)}