在 React Native 中获取后将数据添加到 Json
Add data to Json after fetch in React Native
我有一个 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 }
首先,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,
}
});
}
我有一个 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 }
首先,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,
}
});
}