Javascript react本机洗牌平面列表数组
我试图添加一个按钮来洗牌数组,但是当页面加载时,平面列表会被洗牌 这里有一个数组:Javascript react本机洗牌平面列表数组,javascript,react-native,react-native-flatlist,Javascript,React Native,React Native Flatlist,我试图添加一个按钮来洗牌数组,但是当页面加载时,平面列表会被洗牌 这里有一个数组: constructor(props) { super(props); this.state = { deck: [ { id: Math.random(), text: "0" }, { id: Math.random(), text: "1" }, { id: Math.random(),
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" },
],
};
}
现在是shuffle函数
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>
(
{item.text}
)}
/>
我只想在按下按钮时洗牌,我错过了什么
我现在可以在屏幕上加载未缓冲的数组,但现在按下“无序”按钮时无法更新数组 根据下面的注释,这里是更新的代码
<TouchableOpacity
style={styles.btn}
onPress={() => {
this.setState({ deck: this.shuffleDeck(this.state.deck) });
}}
>
<Text style={styles.btnText}>Shuffle</Text>
</TouchableOpacity>
{
this.setState({deck:this.shuffleDeck(this.state.deck)});
}}
>
洗牌
尝试将onPress更改为箭头功能:
onPress = {() => this.shuffleDeck(this.state.deck)}
如果删除洗牌组方法会发生什么情况?@evolutionxbox哦,是的,我忘了提到,数组按0-9的顺序显示。您可以使用日志记录来确保洗牌方法没有在加载时被调用。@evolutionxbox是,但我不明白,如果你不使用一个属性,而是把它变成一个实际的方法,为什么会这样呢。否则将立即调用该函数。谢谢。虽然它确实解决了问题,但我是否需要为列表添加更多代码以刷新或显示无序列表?@gSaenz不确定您是否已解决此问题。如果没有,我可以解释。为了实际更改状态中的数据,必须调用名为setState的react组件的方法。setState获取一个对象,然后该对象与以前的状态合并。在react文档中有更好的解释:如果不这样做,您必须调用setState来更新它。我会把你的onPress改为:onPress={()=>{this.setState({cards:this.shuffleDeck(this.state.deck)}}}->希望如此helps@NickD啊,是的,我尝试使用
setState
但是在shuffle函数中。我知道这不是一个合适的地方,我也尝试了一下,但仍然没有解决这个问题。文档没有设置状态
,这就是为什么我一开始没有尝试。另外,请注意,我将按shuffle改为可触摸不透明度,而不是
,我在上面更新以供参考。思考是为什么仍然不起作用,如果需要,我可以打开新的问题。因为事实证明,我在平面列表中也缺少extraData={this.state}
prop。