【问题标题】:mapping json from a fetch function into setstate将 json 从 fetch 函数映射到 setstate
【发布时间】:2020-02-16 13:44:49
【问题描述】:

我正在尝试将 json 响应映射到一个状态,我想要做的是映射这个数组的所有子元素,无论有多少,就像跳过第一个数组并只显示它的子元素一样,这就是我的试着做

fetch(api).then((response) => {
  response.json()  .then((data) => {
    data.children.map( (menu) => {

      this.setState({
        mydata: menu
      })
}) console.log("test", this.state.mydata )})  
    });

这是我从 api 收到的内容

  {
    "name": "Store 1",
    "children": [
      {
        "name": "Store 1",
        "children": [{},{}...]
      },
      {
        "name": "Store 2",
        "children": [{},{}...]
      }
    ]
  }

这就是我希望它存储在我的状态中的方式,

[
          {
            "name": "Store 1",
            "children": [{},{}...]
          },
          {
            "name": "Store 2",
            "children": [{},{}...]
          }
      ]

【问题讨论】:

  • 在同一 key 上循环调用 this.setState() 是个问题..
  • 我的目标是将它们映射并存储到一个状态,而不是存储它然后在渲染返回中映射它
  • 我建议映射您的数组,然后将其设置为状态一次。

标签: javascript arrays json reactjs mapping


【解决方案1】:

没有必要映射它。你应该把它放入状态。

fetch(api)
 .then(response => response.json())
 .then(data => this.setState({
  myData: data.children
 }))

【讨论】:

    猜你喜欢
    • 2020-06-08
    • 2022-12-31
    • 2019-09-18
    • 2023-03-11
    • 1970-01-01
    • 2019-05-27
    • 2015-02-14
    • 1970-01-01
    • 2020-05-16
    相关资源
    最近更新 更多