我的問題:
目前,我正在嘗試使用 React 和 AntDesign 為我的 Web 應用程式開發考試/測驗模式。我的問題是:當我點擊“測驗”按鈕提交測驗時。整個函式,包括常量和問題,重新加載。這會產生全新的問題和答案,并導致我無法使用正確答案檢查提交的答案。
這是應該只運行一次的部分:
// Generates ten random questions from inputted JSON file
const array = []
for (let i = 1; i <= question.length; i ) {
array.push(i)
}
const result = [];
for (let j = 1; j <= 10; j ) {
const random = Math.floor(Math.random() * (question.length - j));
result.push(array[random]);
array[random] = array[question.length - j];
}
// Random shuffles the answers of the questions
const answerarray = []
for (let k = 1; k <= 4; k ) {
answerarray.push(k)
}
const answerresult = [];
for (let l = 1; l <= 4; l ) {
const arandom = Math.floor(Math.random() * (4 - l));
answerresult.push(answerarray[arandom]);
answerarray[arandom] = answerarray[4 - l];
}
我嘗試過的:
- 我試過使用 Hooks
useMemo(),useEffect()但無濟于事。這會導致“無法讀取未定義的屬性”錯誤。 - 我還嘗試隔離
DisplayQuestions.js檔案的某些部分(請參閱 CodeSandbox 的鏈接)。由于<Form>AntD 使用的組件,這導致“測驗”按鈕不起作用。(它必須在一個檔案中。)
CodeSanbox 鏈接: https ://codesandbox.io/s/problem-wym5m ? file =/ src/App.js
我希望有人能幫助我解決我的問題。提前致謝!
uj5u.com熱心網友回復:
呼叫您只想在useEffect空依賴陣列中運行一次的函式(在您的情況下是生成隨機的函式)并將結果存盤在狀態變數中。
樣本:
import { useEffect, useState } from "react";
export default function App() {
const [count, setCount] = useState(5);
const [count2, setCount2] = useState(7);
useEffect(() => {
setCount(Math.random()*10)
console.log('jjj')
}, []);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>count: {count} and count2: {count2}</h2>
<button onClick={()=>setCount2(count2 1)}>Count2 </button>
</div>
);
}
這里計數只會改變一次。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/396983.html
上一篇:我想在按下按鈕時呼叫API
