簡體   English   中英

將 json 從 fetch function 映射到 setstate

[英]mapping json from a fetch function into setstate

I am trying to map a json response into a state, what I am trying to do is map all the children of this array no matter how many, as in skipping the first array and only show its children, here is what i tried to do

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": [{},{}...]
      }
    ]
  }

這就是我希望它存儲在我的 state 中的方式,

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

沒有必要 map 它。 您應該將其放入 state 中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM