javascript - 如何将来自 json API 响应的数据存储到 ReactJS 中的数组中?

标签 javascript arrays reactjs object ecmascript-6

所以我设置了一个数据库,我试图从中提取信息并将其存储到状态数组中,以便我可以在网站上使用它。

这是我从数据库请求时得到的示例,为便于阅读而缩短

{
    "count": 10,
    "next": null,
    "previous": null,
    "results": [
        {
            "var1": "Test",
            "var2": "",
            "NeededInfo": "name1",
        },
        {
            "var1": "Test",
            "var2": "",
            "NeededInfo": "name2",
        }
    ]
}

所以我需要的是获取每个对象的 NeededInfo 并将其存储到一个数组中,以便我可以在 render() 上使用它。这就是我正在尝试的,但是当我执行 printToConsole()(未显示,只是一个 console.log(this.state))来查看状态数组的样子时,“其他”数组未定义

const title_URL = "http://123.456.789/namelist";

class Project extends Component {
  constructor(props) {
    super(props);

    this.state = {
      random1: "",
      random2: "",
      other: [],
      items: []
    }
  }

  componentDidMount() {
    fetch(title_URL)
      .then(response => {
        return response.json();
      })
      .then(data => {
        this.setState({
          other: data.results.NeededInfo
        })
      });
  }

我需要“其他”数组看起来像

other: ["name1", "name2"]

因为在我的 render() 中,我必须列出站点从数据库中提取的名称,以便用户可以看到所列项目的名称并用它做一些其他事情,然后我可以将其保存到“items”数组,以新的顺序排列,但如果我有一个预设的“其他”数组,那部分就可以使用。

最佳答案

您需要从结果中获取 NeededInfo 并将其插入临时数组(仅存储 NeededInfo 值),然后将其设置为状态。例如:

componentDidMount() {
    fetch(title_URL)
        .then(response => {
            return response.json();
        })
        .then(data => {
            // Here you need to use an temporary array to store NeededInfo only 
            let tmpArray = []
            for (var i = 0; i < data.results.length; i++) {
                tmpArray.push(data.results[i].NeededInfo)
            }

            this.setState({
                other: tmpArray
            })
        });
}

关于javascript - 如何将来自 json API 响应的数据存储到 ReactJS 中的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56783262/

相关文章:

c++ - 如何将数据从用户输入到2D数组中,并输出到用户C++

c++ - 使用指针和线性搜索在数组中找到更大和最小的数字?

javascript - 在原生 Android View 中渲染 React-Native 组件(UI 组件)

node.js - 尝试使用 this.refs.value 时,使用 this.refs 已被弃用错误

javascript - Handlebars 、JS 和 Node

Javascript、正则表达式 - 我需要获取带有参数的条目,可能跨多行

javascript - 输入后,在 db 中搜索字符串

javascript - 使用绝对将元素放在其他元素内。元素是 sibling

java - 在 Java 中将 vector 作为参数发送

reactjs - 在 React 中使用包装组件来传递 props 可以吗?