我做了這家店:
export class CommentStore {
comments = []
constructor() {
makeAutoObservable(this, {}, { autoBind: true });
}
async loadPostComments(postId: number): Promise<void> {
const res = await API.loadPostComments(postId);
runInAction(() => {
this.comments = res;
});
}
async sendComment(postId: number, comment: Comment): Promise<void> {
try {
await API.sendComment(postId, comment);
await this.loadPostComments(postId);
return true;
} catch (err) {
console.log('oops');
}
}
}
我需要在反應組件中使用 await 嗎?例如:
useEffect(() => {
(async function () {
await loadPostComments(postId);
})();
}, [loadPostComments, postId]);
但這也很好用:
useEffect(() => {
loadPostComments(postId);
}, [loadPostComments, postId]);
sendComment onClick 也一樣:
onClick={()=>{sendComment(postId, comment)}}
onClick={async ()=>{await sendComment(postId, comment)}}
那么,在這種情況下是否有必要使用await呢?
uj5u.com熱心網友回復:
await只有在必要時才想要某些東西,例如,當下一行代碼使用來自 Promise 的資料時。在您提供的 useEffect 案例中,它不是必需的,并且在 onClick 處理程式上也是如此
uj5u.com熱心網友回復:
是的,沒有必要在它們上面寫 async/await。你只需要在函式上撰寫異步呼叫就足夠了。
例如:
const [posts, setPosts] = useState([]);
useEffect(() => {
const loadPost = async () => {
// Await make wait until that
// promise settles and return its result
const response = await axios.get(
"https://jsonplaceholder.typicode.com/posts/");
// After fetching data stored it in some state.
setPosts(response.data);
}
// Call the function
loadPost();
}, []);
` 不需要對所有內容都寫 promise 和 async/await,記住;P
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/398412.html
標籤:javascript 反应 异步 移动版
