我需要在react组件中使用等待异步操作吗



我做了这个商店:

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');
}
}
}

我需要在react组件中使用wait吗?例如:

useEffect(() => {
(async function () {
await loadPostComments(postId);
})();
}, [loadPostComments, postId]);

但这也很好:

useEffect(() => {
loadPostComments(postId);
}, [loadPostComments, postId]);

与sendComment相同点击:

onClick={()=>{sendComment(postId, comment)}}
onClick={async ()=>{await sendComment(postId, comment)}}

那么,在这种情况下有必要使用等待吗?

只有在必要的情况下,例如当下一行代码使用Promise中的数据时,才需要await。在您提供的useEffect情况下,它是不必要的,并且在onClick处理程序以及上

是的,没有必要在它们上写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

最新更新