我是否需要在 React 组件中使用 await 进行异步操作?
Do I need to use await for async actions in react components?
我开了这家店:
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 组件中使用 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吗?
你想 await
只有在必要时才做某事,例如当下一行代码使用来自 Promise 的数据时。
在您提供的 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
我开了这家店:
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 组件中使用 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吗?
你想 await
只有在必要时才做某事,例如当下一行代码使用来自 Promise 的数据时。
在您提供的 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