我能夠在控制臺中顯示資料,但無法使用 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
}
]
}
反應頁面的螢屏截圖更清晰
uj5u.com熱心網友回復:
您正在使用 await 將資料設定為“then”函式,因此,首先設定資料,然后將加載設定為 true,現在您的加載保持在螢屏上。
您需要先設定加載,然后設定資料。
uj5u.com熱心網友回復:
您從 API 呼叫中獲得的回應包括一個名為data. 您res.data通過嘗試訪問來將其視為物件res.data.info。這將回傳未定義,因此您永遠不會更新您的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;
uj5u.com熱心網友回復:
嘗試使用res.info而不是res.data.info
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470975.html
標籤:javascript 反应
