[英]Fetching data from JSON in React Native
我是 React Native 的新手。 我在 Firebase 上获取数据,但我想获取它的 JSON 文件。 我的 JSON 文件是这样的:在此处输入图像描述
如何将 firebase url 更改为我的 php json url? 请帮助我这是我的代码:
return async (dispatch, getState) => {
// any async code you want!
// const userId = getState().auth.userId;
try {
const response = await fetch(
'https://shopapp-f9964.firebaseio.com/products.json'
);
if (!response.ok) {
throw new Error('Something went wrong!');
}
const resData = await response.json();
const loadedProducts = [];
for (const key in resData) {
console.log(resData[key].description);
loadedProducts.push(
new Product(
0,
0,
resData[key].product_image,
resData[key].description,
resData[key].price,
)
);
}
dispatch({
type: SET_PRODUCTS,
products: loadedProducts,
//userProducts: loadedProducts.filter(prod => prod.ownerId === userId)
});
} catch (err) {
// send to custom analytics server
throw err;
}
};
这是从 API(或 Json 响应)获取的方法。
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
这是官方文档,它确实有助于您理解 JSON 文件中的数据
https://reactnative.dev/docs/network
这是Snack的工作示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.