【问题标题】:Add data to Json after fetch in React Native在 React Native 中获取后向 Json 添加数据
【发布时间】:2017-01-29 16:31:49
【问题描述】:

我有一个 api 客户端,可以很好地从网站中的 Json 获取信息。我想要的是在从网站获取后向该内容包添加一些新行。

我了解了 .push 函数,但不知道在哪里放入新的 ES6 格式,也无法在 Google 中找到任何信息。

我正在使用:

react-native-cli: 2.0.1
react-native: 0.40.0

这是代码:

const BASE_URL = 'https://example.com/data.json';

customData = [
  {
    autor: 'Mike',
    category: 'category name',
  }
]

function getJsonData() {
  return fetch(BASE_URL)
    .then(response => response.json())
    .then(data => data.items.item)
    .then(myData => myData.push(customData)) // <- Trying to add custom data
    .then(news => news.map(item => {
      return {
        autor: item.author,
        category: item.category,
      }
    })
  )
  //.then(news => news.push(customData)) // <- Also I tried here
}

export { getJsonData }

【问题讨论】:

    标签: json react-native fetch


    【解决方案1】:

    首先,data.items.item 没有返回可以与then 一起使用的 Promise。

    使用 async/await 来省事:

    async function getJsonData() {
        const response = await fetch(BASE_URL);
        const json = await response.json();
    
        // Not clear what you're trying to accomplish here but should give
        // you an idea
        data.items.push(customData);
        return json.items.map((item) => {
           return {
             autor: item.author,
             category: item.category,
           }
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多