React Native中的递归解析JSON树

时间:2019-04-19 11:34:26

标签: javascript reactjs react-native

我正在尝试使用react native显示reddit帖子的评论。由于从API返回的JSON始终是嵌套的注释数,因此我想解析JSON的最佳方法是使用递归。 要在subreddit中获取帖子的评论,可以使用以下网址,我已经链接了一个示例。

https://www.reddit.com/r/${subreddit}/comments/${postId}.json

下一步,我使用递归函数在JSON树中移动并找到具有body属性的任何对象并将其推入数组。

parseComments(comments, i, j) {
    for (let property in comments) {
      if (comments.hasOwnProperty(property)) {
        if (property === "replies") {
          this.parseComments(comments[property], i, j);
        } else if (typeof comments[property] === "object") {
          if (comments[property] != null) {
            if (comments[property].body != undefined) {
              this.setState(prevState => ({
                commentStrings: [...prevState.commentStrings,
                  ".".repeat(j) + comments[property].body
                ]
              }));
              j += 1;
            }
            this.parseComments(comments[property], i, j);
          }
        }
      } 
    }
  }

我正在使用Expo调试和测试手机上的代码,但是当代码进入递归功能时,它只会冻结在那里。

是否存在导致此问题的CPU或内存限制,以及在此示例JSON中显示注释的最佳方法是什么?

0 个答案:

没有答案