首页 > 解决方案 > 获取类型错误无法解构属性,因为它在 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};

}

下图显示了之后的结果console.log(posts)在此处输入图像描述

标签: reactjs

解决方案


您试图在没有先获取数据的情况下解构一个值。所以,你得到一个错误。

当没有任何数据时,您正在为帖子运行以下代码

 const onePostId=posts.postId

并且只有在调用

    getOnePost();

您的数据已被填充,但您应该始终考虑使用 async await 语法存在时间延迟,并且您应该首先检查帖子是否包含带有某个值或是否已定义的 post.postId,然后进行解构。如果没有,那么可能不使用它,要么等待它,要么返回加载或返回模拟值。

例如:

if(!posts.postId){
        //  posts.postId is not set and it doesn't have data 
}

推荐阅读