Jus*_*tin 2 javascript reactjs redux react-redux
我有一个 Q/A 对象的减速器数组。我将它们设置为两个不同的 div。我需要“下一步”按钮来触发一个函数,该函数将生成一个随机数,该随机数将确定要从数组中显示的下一个对象。“下一步”按钮成功触发了该函数,并且该函数成功创建了一个随机数,但问答道具并没有根据随机数发生变化。如何生成随机数并使用该数字从数组中选择对象?
这是我的代码GitHub
首先,我会摆脱类结构,改用函数组件。其次,摆脱 setState 等。使用较新的 React hooks: https: //reactjs.org/docs/hooks-state.html
你的代码可读性将会大大提高。
import React, {useState} from "react";
const questionAnswer: [
{question: "Question 1", answer: "Answer 1"},
{question: "Question 2", answer: "Answer 2"},
{question: "Question 3", answer: "Answer 3"},
{question: "Question 4", answer: "Answer 4"}
];
export const FlashCards = ({questionAnswer}) => {
const [randomNumber, setRandomNumber] = useState(0)
const flipDisplay = () => {
// Logic flip display here.
}
const generateRandomNumber = () => {
const randomNumber = Math.floor(Math.random() * questionAnswer.length);
setRandomNumber(randomNumber)
}
return (
<div className='ui container'>
<div id='question'>
{questionAnswer[randomNumber].question}
</div>
<div id='answer' style={{display: 'none'}}>
{questionAnswer[randomNumber].answer}
</div>
<div>
<button className='ui button' onClick={flipDisplay}>Flip</button>
<button className='ui button' onClick={generateRandomNumber}>Next</button>
</div>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8790 次 |
| 最近记录: |