【发布时间】:2020-04-07 20:49:49
【问题描述】:
我正在使用 React 构建一个抽认卡应用程序来帮助保留编程概念。到目前为止,我已将应用程序设置为在卡片的正面显示带有概念定义/解释的卡片,并在背面显示相应的术语/概念。用户可以通过单击按钮翻转卡片并更改为不同的卡片。问题是目前,onClick 有时会显示之前显示的卡片。我想防止这种情况发生。我尝试使用三元运算符这样做,但不知何故,我的 Javascript 逻辑是错误的,因为我仍然得到重复显示。我该如何解决这个问题?
代码如下:
// data and components
import { conceptArray } from "./data";
import FlashCard from "./components/FlashCard";
function App() {
const [randomCard, setRandomCard] = useState({});
const [mode, setMode] = useState(true);
// this should store the individual concept (individual items in the concept Array) to later be displayed as a card
const getCard = () => {
// this changes the card and posits that there can be no repeat display of card that was displayed immediately before
let newCard = conceptArray[Math.floor(Math.random() * conceptArray.length)];
newCard !== randomCard ? setRandomCard(newCard) : newCard = conceptArray[Math.floor(Math.random() * conceptArray.length)];
// this allows for the front of the card(ie. the definition) to be displayed
setMode(true);
};
const flip = () => {
// this allows for the back of the card (ie. the term itself) to be displayed
setMode(!mode);
}
console.log(randomCard);
return (
<div className="App">
<header className="App-header">
<FlashCard randomCard={randomCard} mode={mode} />
<button onClick={getCard}>Get FlashCard</button>
<button onClick={flip}>Flip</button>
</header>
</div>
);
}
export default App;
【问题讨论】:
-
如何保留一个存储最后三个随机(数字)的数组并将每个新数组与您拥有的数组进行比较
-
这听起来比它需要的更复杂。但我愿意考虑这一点。你能建议这个代码吗? @米莎
-
如何将conceptArray 洗牌进入状态。然后每次选择一张卡片时取出数组中的第一项(用其余的更新状态)。当状态为空时,你重新洗牌概念数组...
-
这难道不是把卡片整理好@ThomasWikman 吗?我实际上希望卡片顺序是随机的。
-
把它想象成一副纸牌。你洗牌,拿走最上面的牌。你只需要在重新洗牌之前弄清楚你是否希望选择的牌再次回到牌组中,或者你是否希望牌组是空的。
标签: javascript reactjs onclick conditional-operator