我正在尝试构建一个显示随机问题的简单应用。我可以在挂载和页面刷新时成功显示数组中的随机字符串。
我想显示一个不同的按钮“ onClick”随机问题,而不是刷新页面?
到目前为止,这里的代码:
export const QuestionContainer = () => {
const [response, setResponse] = useState({});
useEffect(() => {
fetchData().then(res => setResponse(res));
}, []);
const { records = [] } = response;
const questions = records.map(record => record.fields.question);
console.table(questions);
// const randomNum = arr => {
// return Math.floor(Math.random() * arr.length);
// };
return (
<div className='questions-container'>
<h1>{questions[0]}?</h1>
<button onClick={() => console.log('more')}>More</button>
</div>
);
};
const questions
是一个字符串数组示例-['hello','world','noob问题']
答案 0 :(得分:1)
您非常亲密!只需使用onClick设置要显示的索引,就可以了!这应该起作用:
const randomIndex = (arr) => { // returns a random int value to use as an index
return Math.floor(Math.random() * arr.length)
}
export const QuestionContainer = () => {
const [response, setResponse] = useState({});
const [index, setIndex] = useState(0) // 0 initially, as you had in your example
useEffect(() => {
fetchData().then(res => setResponse(res));
}, []);
const { records = [] } = response;
const questions = records.map(record => record.fields.question);
console.table(questions);
return (
<div className='questions-container'>
<h1>{questions[index]}?</h1>
<button onClick={_ => setIndex(randomIndex(questions)}>More</button>
</div>
);
};