【发布时间】:2021-11-22 06:45:52
【问题描述】:
在这里反应菜鸟。
我很难理解 useEffect 和 useState 挂钩的工作原理。
我的应用程序获取检索时需要呈现的数据。
我正在使用 then() 函数来确保以正确的顺序定义变量。我还尝试使用多个 useEffect() 函数来保证正确的年表。但是,无论出于何种原因,我的 current 变量是未定义的。它仅在第一次渲染时定义。
import React, { useEffect, useState } from 'react'
export default function Answers() {
const [questions, setQuestions] = useState([])
const [current, setCurrent] = useState()
useEffect(() => {
fetch('http://localhost:8000/questions')
.then(res => res.json())
.then(data => setQuestions(data))
.then(setCurrent(questions[0]))
}, [])
return (
<div>
<ul>
{console.log(current['answers'])}
{current['answers'].map(item => <li>{item}</li>)}
</ul>
</div>
)
}
这是正在获取的数据:
{
"questions": [
{
"id": 1,
"question": "to work",
"answers": ["yapmak", "gitmek", "çalışmak", "gelmek"],
"correct": 3
},
{
"id": 2,
"question": "to know",
"answers": ["gitmek", "bilmek", "çalışmak", "gelmek"],
"correct": 2
},
{
"id": 3,
"question": "to want",
"answers": ["istemek", "gitmek", "çalışmak", "konuşmak"],
"correct": 1
}
]
}
【问题讨论】:
-
您可以分配一个初始值,以便它可用于第一次渲染。
const [questions, setQuestions] = useState([ { "id": 1, "question": "to work", "answers": ["yapmak", "gitmek", "çalışmak", "gelmek"], "correct": 3 }, { "id": 2, "question": "to know", "answers": ["gitmek", "bilmek", "çalışmak", "gelmek"], "correct": 2 }, { "id": 3, "question": "to want", "answers": ["istemek", "gitmek", "çalışmak", "konuşmak"], "correct": 1 } ])
标签: javascript reactjs frontend use-effect