数据显示在控制台,而不是在屏幕- react js



我能够在控制台中显示数据,但无法使用react在DOM页面中显示相同的数据。我看到过这个问题,但是没有一个答案对我有效。你能告诉我我要去哪里吗?我访问错误的信息在SetData()

function Test() {
const [loading, SetLoading] = useState(false);
const [questions, SetData] = useState(null);
const getData = async () => {
try {
const info = await axios.get("http://localhost:3000/info").then((res) => {
console.log(res);
SetData(res.data.info);
});
SetLoading(true);
} catch (err) {
console.log(err);
}
};
useEffect(() => {
getData();
}, []);

return <div>{loading ? questions : <ReactBootstrap.Spinner animation="border" variant="success" />}</div>;
}
export default Test;
API数据格式:
{
"info": [
{
"question": "Angular 2 integrates easily with NativeScript, allowing you to code your native app in a . . . . . . . . . style that can run on any mobile device platform.",
"options": ["a) declarative", "b) imperative", "c) interrogative", "d) exclamatory"],
"answer": 0,
"id": 0
},
{
"question": "Angular 2 components can be described using ________is a way to do some meta-programming.",
"options": [
"a) controllers, controller",
"b) Loaders, loader",
"c) typescripts, typescript",
"d) decorators, decorator"
],
"answer": 3,
"id": 1
},
{
"question": "The ______ directive substitutes the normal href property and makes it easier to work with route links in Angular 2.",
"options": ["a) RouterLink", "b) RouterRend", "c) RouterLike", "d) RouterLayer"],
"answer": 0,
"id": 2
}
]
}

反应页面的截图,更清晰

您从API调用中获得的响应包括一个名为data的数组。通过尝试访问res.data.info,您将res.data视为对象。这将返回undefined,因此您永远不会更新您的questions状态。我在下面重写了你的代码。我希望这将工作(如果它没有,这是在正确的方向迈出的一步)。我也改变了它,当getData()被调用时,发生的第一件事是loading被设置为true,然后进行API调用,然后loading被设置回false。

function Test() {
const [loading, setLoading] = useState(true);
const [questions, setQuestions] = useState();
const getData = async () => {
try {
setLoading(true)
await axios.get("http://localhost:3000/info").then(res => {
setQuestions(res.data);
setLoading(false);
});
} catch (err) {
console.log(err);
}
};
useEffect(() => {
getData();
}, []);

return <div>
{loading ? <ReactBootstrap.Spinner animation="border" variant="success" /> : questions}
</div>;
}
export default Test;

您正在将数据设置为"then"函数与await,所以,首先设置数据,并设置为true后,现在你的加载保持在屏幕上。

你需要先设置加载,然后再设置数据

const getData = async () => {
try {
//First set loading in true
SetLoading(true);
//Then call request
const info = await axios.get("http://localhost:3000/info").then((res) => {
console.log(res);
//Set data in state
SetData(res.data.info);
//remove loading to display the data
SetLoading(false);
});

} catch (err) {
console.log(err);
}
};

最新更新