【问题标题】:won't let me access json object, what im missing?不会让我访问 json 对象,我缺少什么?
【发布时间】: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 不是函数,forEachundefined, 我试图对其进行键值,但值返回给我[object object]undefined

我错过了什么?

【问题讨论】:

  • 欢迎来到 Stack Overflow!请使用tour(您将获得徽章!),环顾四周,并阅读help center,尤其是How do I ask a good question?,我还推荐Jon Skeet 的Writing the Perfect Question
  • 您的代码没有使用mapforEach。您需要提供一个minimal reproducible example(并修复代码中的空白,真的很难阅读)
  • 如果没有更多信息,很难为您提供帮助,但有一件事是您似乎期待来自 fetch 调用 (res._embedded.articles) 的数组,您将其设置为 data在你的状态,但你的初始状态是{},一个非数组对象。因此,您至少应该将data 的初始状态更改为[](一个空数组)。但是再一次,除此之外很难提供帮助,而且当isLoading 为真时,我不希望您使用data...
  • 旁注:这不是问题,但您的代码已被fetch footgun (这是我贫血的小博客上的帖子)。在调用 json() 之前,您应该检查 HTTP 是否成功。

标签: javascript arrays json reactjs object


【解决方案1】:

您将数据作为对象 {} 初始化,第一次渲染从初始状态获取 data

this.state = {
  data: {},
  isLoading: true
}

改成数组

this.state = {
  data: [],
  isLoading: true
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2010-10-29
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多