【发布时间】:2020-10-26 09:48:47
【问题描述】:
所以我正在尝试访问对象内的数组:
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: {},
isLoading: true
}
};
componentDidMount() {
fetch(`https://m0n5ter-crawler.herokuapp.com/api/articles/`, {
method: "GET",
})
.then(res => res.json(res))
.then(res => {
this.setState({
data: res._embedded.articles, //this is where im entering the array of objects
isLoading: false
})
})
.catch((err => {
console.error(err);
}));
}
render() {
const {
isLoading,
data
} = (this.state);
console.log(data);
}
}
这是我在控制台日志中得到的:
(1000) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
[0 … 99]
0: {groups: Array(1), date: "2015-12-03", url: "https://www.scmagazine.com", title: "", _links: {…}}
1: {groups: Array(1), date: "2018-10-19", url: "https://www.scmagazine.com/", title: "", _links: {…}}
2: {groups: Array(1), date: "2018-06-26", url: "https://www.scmagazine.com", title: ""
[100 … 199]
[200 … 299]
[300 … 399]
[400 … 499]
[500 … 599]
[600 … 699]
[700 … 799]
[800 … 899]
[900 … 999]
length: 1000
__proto__: Array(0)
map 不是函数,forEach 是 undefined,
我试图对其进行键值,但值返回给我[object object] 或undefined。
我错过了什么?
【问题讨论】:
-
欢迎来到 Stack Overflow!请使用tour(您将获得徽章!),环顾四周,并阅读help center,尤其是How do I ask a good question?,我还推荐Jon Skeet 的Writing the Perfect Question。
-
您的代码没有使用
map或forEach。您需要提供一个minimal reproducible example(并修复代码中的空白,真的很难阅读) -
如果没有更多信息,很难为您提供帮助,但有一件事是您似乎期待来自
fetch调用 (res._embedded.articles) 的数组,您将其设置为data在你的状态,但你的初始状态是{},一个非数组对象。因此,您至少应该将data的初始状态更改为[](一个空数组)。但是再一次,除此之外很难提供帮助,而且当isLoading为真时,我不希望您使用data... -
旁注:这不是问题,但您的代码已被
fetchfootgun (这是我贫血的小博客上的帖子)。在调用json()之前,您应该检查 HTTP 是否成功。
标签: javascript arrays json reactjs object