reactjs - 获取类型错误无法解构属性,因为它在 React 中未定义
问题描述
我有一个 MongoDB 集合,在这个集合中,有一些文档。在这些文档中,我存储了另一个集合文档的一些 ID。这是本文档的图像。
在前端,我访问此文档并获取postId
. 我试过这种方式。
const onePostId=posts.postId
console.log(onePostId);
const type=typeof (onePostId);
console.log(type);
这个代码部分给了我这个结果。
我尝试以这种方式将其传递postId
给 API const response = await axios.get(`/buyerGetOnePost/${onePostId}`)
。但这postId
是一个字符串类型,我认为这就是为什么我无法从此 API 获得结果。然后我像这样尝试const {onePostId}=posts.postId
然后我收到一个错误,上面写着“TypeError:无法解构'posts.postId'的属性'onePostId',因为它是未定义的”。我该如何解决这个问题?
这是我尝试过的完整代码。
function PostsLocation() {
const { offerId } = useParams();
console.log(offerId);
const [posts, setPosts] = useState({});
useEffect(()=>{
getOnePost();
}, []);
const getOnePost = async () => {
try {
const response = await axios.get(`/buyerGetOneSellerOffer/${offerId}`)
console.log(response);
const allPost=response.data.oneOffer;
setPosts(allPost);
} catch (error) {
console.error(`Error: ${error}`)
}
}
console.log(posts);
const onePostId=posts.postId
console.log(onePostId);
const type=typeof (onePostId);
console.log(type);
const [offerPosts, setOfferPosts] = useState({});
useEffect(()=>{
getOneOfferPost();
}, []);
useEffect(()=>{
if (offerPosts && offerPosts.location) {
console.log(offerPosts.location);
console.log(offerPosts.location.longitude);
console.log(offerPosts.location.latitude);
}
}, [offerPosts]);
const getOneOfferPost = async () => {
try {
const response = await axios.get(`/buyerGetOnePost/${onePostId}`)
console.log(response);
const allOfferPost=response.data.onePost;
setOfferPosts(allOfferPost);
} catch (error) {
console.error(`Error: ${error}`)
}
}
console.log(offerPosts);
const long = offerPosts?.location?.longitude;
console.log(long);
const lat=offerPosts?.location?.latitude;
console.log(lat);
const location={lat,long};
}
解决方案
您试图在没有先获取数据的情况下解构一个值。所以,你得到一个错误。
当没有任何数据时,您正在为帖子运行以下代码
const onePostId=posts.postId
并且只有在调用
getOnePost();
您的数据已被填充,但您应该始终考虑使用 async await 语法存在时间延迟,并且您应该首先检查帖子是否包含带有某个值或是否已定义的 post.postId,然后进行解构。如果没有,那么可能不使用它,要么等待它,要么返回加载或返回模拟值。
例如:
if(!posts.postId){
// posts.postId is not set and it doesn't have data
}
推荐阅读
- java - Spring/JPA - 最好的查询方式
- r - leaflet() draws shapefile as giant rectangle
- r - knitr 在缓存 = TRUE 的 Stan 块上失败
- javascript - 带有graphql-yoga的子字段上的Graphql错误
- python - 加载图像返回函数 cv::inRange 中的断言失败
- c# - 如何将 `Tick` 事件连接到我的计时器?
- python - 从 check_output 抑制标准输出,但将其写入日志
- javascript - 使用 html 和 css 的 PDF 类型视图。页面溢出问题
- sql - 使用子查询更新表
- linux - 为什么“克隆或下载”按钮不将其 URL 复制到我的主要选择?