【发布时间】:2021-10-08 01:17:15
【问题描述】:
我是新手,我尝试从后端获取数据并显示。
const { id } = useParams();
console.log(id);
const [posts, getPosts] = useState([]);
useEffect(()=>{
getOnePost();
}, []);
const getOnePost = async () => {
await axios.get(`/buyerGetOnePost/${id}`)
.then ((response)=>{
const allPost=response.data.onePost;
getPosts(allPost);
})
.catch(error=>console.error(`Error: ${error}`));
}
console.log(posts);
console.log(posts.location.latitude);
console.log(posts.location.longitude);
我传递了一个 id 并从后端获取数据,它工作正常。但是,当我尝试获取该位置的纬度和经度时,会出现如下错误:
TypeError: 无法读取未定义的属性“纬度”
当我这样写代码时:
console.log(posts.location);
console.log(posts.location);
它没有给出任何错误。但是当我尝试访问位置对象中的数据时,它会给出上述类型错误。
This is a screenshot of location object
console.log(posts);
这给出了整个帖子的输出。
就像这张图片。在帖子内部,有一个名为 location 的对象。在 location 对象中,它有一个 Id、经度和纬度。当我console.log(posts.location) 这样做时,位置对象会打印在控制台中。但是当我想访问位置对象中的经度和纬度时,它会报错。
我该如何解决这个问题?
【问题讨论】:
-
您会添加
console.log调用的输出吗?请务必提供输出和对象形状的文本描述,并避免外部资产链接。 -
这能回答你的问题吗? Use Async/Await with Axios in React.js
-
@tmarwen 正如你所说,我添加了更多细节。我还没有 10 个声望,所以我无法添加屏幕截图,这就是我添加一些链接的原因。
标签: reactjs