javascript - 错误:输入“承诺”[]' 在更新状态时不能分配给类型 'PostInfo[]'?
问题描述
目前,我有一个获取 API 和更新状态的函数,但是当我将 Promise 分配给状态时它会显示错误
type DataState = {
postList: Array<PostInfo>:
};
const [state, setState] = useState<DataState>({ postList: [] });
const handleClick = (postID: number) => {
const newPostsList = state.postList.map(async post => {
if (post.id === postID) {
const likeType = post.myLike
? ReactionType.NoReaction
: ReactionType.ThumbsUp;
const response = await putLike(postID, likeType); // fetch API
if (typeof response !== 'string') {
return {
...post,
myLike: !post.myLike,
reactionCount: post.myLike
? post.reactionCount - 1
: post.reactionCount + 1,
};
}
return post;
}
return post;
});
setState({
postList: newPostsList, // error here
});
}
我可以通过使用for
循环来解决这个问题
const handleClick = async (postID: number) => {
const posts = state.postList;
const newPostsList = [];
for (let i = 0; i < posts.length; i++) {
if (posts[i].id == postID) {
const likeType = posts[i].myLike
? ReactionType.NoReaction
: ReactionType.ThumbsUp;
const response = await putLike(postID, likeType); // fetch API
if (typeof response !== 'string') {
newPostsList.push({
...posts[i],
myLike: !posts[i].myLike,
reactionCount: posts[i].myLike
? posts[i].reactionCount - 1
: posts[i].reactionCount + 1,
});
} else {
newPostsList.push(posts[i]);
alert(response);
}
} else {
newPostsList.push(posts[i]);
}
}
setState({
postList: newPostsList,
});
}
我该如何解决这个问题但仍在使用map
?感谢您的阅读!
解决方案
错误是真的,因为您将异步数组放入同步数组中,所以我建议您在每次迭代获得响应后立即推送每个列表,如下所示:
type DataState = {
postList: Array<PostInfo>:
};
const [state, setState] = useState<DataState>({ postList: [] });
const handleClick = (postID: number) => {
state.postList.forEach(async post => {
if (post.id === postID) {
const likeType = post.myLike
? ReactionType.NoReaction
: ReactionType.ThumbsUp;
const response = await putLike(postID, likeType); // fetch API
if (typeof response !== 'string') {
setState(prevState => prevState.concat([{
...post,
myLike: !post.myLike,
reactionCount: post.myLike
? post.reactionCount - 1
: post.reactionCount + 1,
}]));
}
return post;
}
return post;
});
}
推荐阅读
- airflow - 如何在 Google Cloud Composer 中从第三方提供商(例如 vault 或 LastPass)访问密码?
- php - 在证书上打印动态内容
- ios - 从 azure 管道构建 ipa 时,okta ionic 插件不起作用
- reactjs - 非常慢的 setState - React
- redirect - 指向 Google Workspace 侧面板中的链接
- networking - 添加随机噪声以使用 netem 发送几 Mbyte 数据
- android - 将数据传递给 Flutter 视图控制器
- javascript - CSS 最大高度转换不适用于 Javascript 类切换
- r - 使用 read_csv 导入时限制 col_type 的选项
- swift - 在 iOS 上使用带有不良网络的 AWS Amplify API