Javascript 如何从数组中生成随机项而不在React.js中重复?
下面是我的代码片段。。我正在开发一个随机报价生成器,希望找到一个解决方案,从阵列中不重复地生成每个随机报价和背景,直到全部使用完毕,然后再次循环。背景图像将直接导入状态,引号数组将从单独的文件导入。我曾尝试从数组中分割每个项目,并将其推入一个空项目,但到目前为止,还没有成功Javascript 如何从数组中生成随机项而不在React.js中重复?,javascript,arrays,reactjs,algorithm,function,Javascript,Arrays,Reactjs,Algorithm,Function,下面是我的代码片段。。我正在开发一个随机报价生成器,希望找到一个解决方案,从阵列中不重复地生成每个随机报价和背景,直到全部使用完毕,然后再次循环。背景图像将直接导入状态,引号数组将从单独的文件导入。我曾尝试从数组中分割每个项目,并将其推入一个空项目,但到目前为止,还没有成功 constructor(props) { super(props); this.state = { quote: quotes[0].quote
constructor(props) {
super(props);
this.state = {
quote: quotes[0].quote,
author: quotes[0].author,
backgrounds: [
photos..
]
};
}
shuffleAll = (arr) => {
return arr.sort(function () { return 0.5 - Math.random() });
}
findRandomQuote = (arr) => {
let num = Math.floor(Math.random() * quotes.length);
let randQuote = quotes[num];
this.shuffleAll(quotes);
this.setState({
quote: randQuote.quote,
author: randQuote.author
});
}
findRandomBackground = (arr) => {
const { backgrounds } = this.state;
let background = backgrounds[Math.floor(Math.random() * backgrounds.length)];
this.shuffleAll(backgrounds);
document.body.style.background = `url(${background})`;
}
您可以使用state存储引号数组,并从中减去,直到所有引号都用完:
constructor(props) {
super(props);
this.state = {
availableQuotes: [...quotes],
activeQuote: null
};
}
findRandomQuote = () => {
const quoteOptions = this.state.availableQuotes.length > 0 ? this.state.availableQuotes : quotes;
const randomIndex = Math.floor(Math.random() * quoteOptions.length);
this.setState({
availableQuotes: [...quoteOptions].splice(randomIndex, 1),
activeQuote: quoteOptions[randomIndex]
});
}
// This runs after component mounts, to set the first random quote
componentDidMount() {
this.findRandomQuote();
}
你可以做一个类似的事情来随机化背景图像。什么是
引号
?请尝试创建一个“我已尝试从数组中分割每个项目并将其推入一个空项目”-还请共享您尝试的代码。quotes正在从包含my quotes数组的单独文件导入,该数组在每个索引中都包含quote和author。之前,我尝试将另一项添加到state,如usedQuotes=[],然后在设置state后,我将quotes.slice(randQuote).push(this.usedQutoes)添加到函数findRandomQuote中,但这不起作用。我还没有完全将此解决方案用于我的代码,但是添加componentDidMount修复了我在页面加载时呈现第一个随机引用时遇到的另一个问题,所以谢谢!!