我不知道如何訪問這個 Promise 物件。如何映射這個承諾?為什么我的 async/await 函式回傳的是 promise 而不是結果物件?任何反饋表示贊賞。
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(2)
0: "hey"
1: "bye"
length: 2[[Prototype]]: Array(0)
import { io } from "socket.io-client";
import { useState, useEffect } from "react";
function App() {
const [text, setText] = useState("");
const [socket, setSocket] = useState();
const [chat, setChat] = useState([]);
useEffect(() => {...}, []);
***//getting previous chat for new users.***
useEffect(async () => {
let mounted = true;
const response = await fetch("http://localhost:4000/main_chat").then(
(res) => {
if (mounted) {
setChat(res.json());
}
}
);
return () => (mounted = false);
}, []);
useEffect(() => {...},[socket]);
const handleClick = () => {
socket.emit("sentFromClient", text);
};
return (
<div>
<ul>{console.log(chat)}</ul>
<input value={text} onChange={(e) => setText(e.target.value)}></input>
<button onClick={() => handleClick()}>enter</button>
</div>
);
}
export default App;
uj5u.com熱心網友回復:
fetch回傳一個你等待的 Promise,然后res.json()回傳另一個你沒有等待的 Promise。這樣 Promise 就會被傳遞給setChat并成為 的值chat。
您還混合了awaitand .then,它們做同樣的事情,所以你可能應該只使用一個或另一個。
與await:
const response = await fetch(...)
const json = await response.json()
setChat(json)
與.then:
fetch(...)
.then(response => {
return response.json()
})
.then(json => {
setChat(json)
})
最后,在呼叫 之前檢查是否仍然掛載是正確的setChat,但是將異步函式傳遞給useEffect將不起作用,因為您需要回傳清理函式 ( () => (mounted = false)),而異步函式回傳 Promises。所以:
useEffect(() => {
let mounted = true
const getChat = async () => {
await whatever...
if (mounted) setChat(something)
}
getChat()
return () => (mounted = false)
})
或者
useEffect(() => {
let mounted = true
fetch(...).then(chat => {
if (mounted) setChat(chat)
})
return () => (mounted = false)
})
uj5u.com熱心網友回復:
您同時使用兩者.then(),async\await這有點令人困惑。也許您應該首先console.log()從回傳的 JSX 運算式中洗掉。然后,在您的 useEffect 鉤子中,將其更新為
useEffect(async () => {
let mounted = true;
const response = await fetch("http://localhost:4000/main_chat")
if (mounted) {
// consol.log(response) here should give you the value returned by the API
setChat(response);
}
// Not sure why are you returning this function definition
return () => (mounted = false);
}, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/397936.html
標籤:javascript 反应 表达
下一篇:ReactHook"useParams"在函式"fetchMentors"中呼叫,該函式既不是React函陣列件也不是自定義ReactHook函式
