【发布时间】:2021-07-13 16:08:34
【问题描述】:
我有这个错误« 错误:TypeError:无法解构'fetchedData'的属性'id',因为它是未定义的。 » 我不知道如何处理它
这是一个使用微 API(端口 3000)的反应应用(端口 3001)。
import Data from "./Data";
export default class Service {
/**
* Fetch the user main data from the API
* @param {function} resolve the function for success
* @param {number} id the user ID
* @return {void}
*/
getData = (resolve, id) => {
fetch(`http://localhost:3000/user/${id}`)
.then((response) => response.json())
.then((result) => {
const data = new Data();
console.log(result)
resolve(data.getData(result.data));
})
.catch((error) => {
console.log("Error: ", error);
})
};
}
控制台日志告诉我«无法获取用户»
这里是数据类
export default class Data {
/**
* Service to handle the fetched data (user data)
* @param {object} fetchedData The data from the API
* @return {object} The formatted data for the front
*/
getData(fetchedData) {
const { id, userInfos } = fetchedData;
const { firstName, lastName, age } = userInfos;
const userObj = new Infos(firstName, lastName, age);
const userDataObj = new MainData(id, userObj);
return userDataObj;
}
}
我不知道如何处理这个错误以及我的错误在哪里。
【问题讨论】:
-
你确定错误信息不是在抱怨解构
fetchedData吗? -
是的,你是对的,对不起。我编辑了我的消息。谢谢。
-
那么当您将
result.data传递给getData()时,它看起来像未定义,而在const { id, userInfos } = fetchedData失败,因为fetchedData 现在未定义。 -
好的,但是当我在获取路径上放置一个有效的 id 而不是 $ {id} 时。 console.log(result.data) 给我我正在寻找的对象。
-
反引号内
${id}的含义与解构{ id } = whatever完全没有关系,所以我对你最后的评论感到困惑。
标签: reactjs