【问题标题】:How to count number of elements in a JSON result with react js如何使用 React js 计算 JSON 结果中的元素数
【发布时间】:2019-01-23 12:12:23
【问题描述】:

我试图获取我的 Json 响应的长度,但它不起作用 我在我的 json 结果中使用了“长度” 这是我在课堂上用 react js 尝试的:

  componentDidMount() {
    axios.get(`http://localhost:51492/api/CommentSurExperience/GetAllCommentOfExperience/${this.props.passedVal}`)
      .then(res => {
        const persons = res.data;
        const longeur = res.length;
        this.setState({ persons, longeur });
      })
  }

然后我返回了这个:

<div> <p> { this.state.longeur}</p> </div>

但我得到了一个空结果。

请问如何计算我的 JSON 响应中有多少元素 谢谢你的帮助。

**********更新*********** 这是我使用邮递员的 JSON 结果

这是一个显示 console.log(res) 显示内容的捕获

【问题讨论】:

  • 您能展示一下res 的样貌吗?
  • 看起来 res 是一个 json 对象而不是一个数组
  • @ChrisR 我更新了我的帖子,捕获了 Json 结果
  • 你能把console.log(res)的结果写在这里吗?
  • 那是邮递员 api 调用,你能 console.log(res) 吗?

标签: json reactjs api count


【解决方案1】:

应该是

const longeur = res.data.length;

【讨论】:

  • 成功了,我只是忘记了“数据”,非常感谢
【解决方案2】:

您需要使用res.data.length。您可以在 Axios docs 中查看响应架构。

【讨论】:

  • 成功了,我只是忘记了“数据”,非常感谢
【解决方案3】:

您必须指定该号码属于您所在州的哪个键:

setState({
  persons: res.data,
  longeur: longeur
})

否则可能是因为你想要的是 res.data.length?

【讨论】:

  • 此符号this.setState({ persons, longeur }); 以隐式方式指定密钥。
  • "res.data.length" 成功了,我只是忘记了"数据",非常感谢
  • 嗯,是的。但他并没有真正指定他的状态变量叫什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
  • 2016-08-27
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
相关资源
最近更新 更多