這就是我想做的:get test info from api > receieve test info > store it on an object "test" > set states "test_title" and "test_desc"> put both "test_name" and "test_desc" as values on my form從 api 獲取測(cè)試信息:useEffect(() => { fetchTest()}, [])const [test, setTest] = useState({})const [test_name, setTestName] = useState("")const [test_desc, setTestDesc] = useState("")// Fetch Testconst fetchTest = () => { let test_code = params.code const url = ...url here... axios.get(url) .then(res => { if (res.status == 200) { setIsGettingData(false) setTest(res.data) // Set Test Name and Desc setTestInfo() } }) .catch(err => { console.log(err.response) })}這用于更新從 api 調(diào)用接收數(shù)據(jù)后調(diào)用的test_nameand :test_desc// Set Test Infoconst setTestInfo = () => { setTestName(test.name) setTestDesc(test.desc)}我的表格:<form id="form_test"> <input type="text" value={test_name} onChange={e => setTestName(e.target.value)} className="form-control mb-2" placeholder="test name" /> <textarea className="form-control" value={test_desc} onChange={e => setTestDesc(e.target.value)} placeholder="test description"></textarea></form>問題是有時(shí)輸入顯示實(shí)際的test_name和test_desc,有時(shí)則不顯示。當(dāng)我控制臺(tái)記錄它時(shí),它有時(shí)會(huì)顯示實(shí)際值,有時(shí)會(huì)顯示未定義。當(dāng)在頁面上正常顯示它時(shí){test_name},就像 一樣,有時(shí)顯示,有時(shí)不顯示。我想這可能是因?yàn)閍pi調(diào)用?就像有延遲或其他什么情況一樣,我猜 DOM 在保存或接收數(shù)據(jù)之前就已經(jīng)渲染了所有內(nèi)容?我不知道。對(duì)此有何建議?多謝!
通過 API 調(diào)用設(shè)置的狀態(tài)值有時(shí)不會(huì)顯示在頁面上(或表單組件上)
楊__羊羊
2023-08-18 10:33:35