【问题标题】:Fetching data from JSON in React Native在 React Native 中从 JSON 获取数据
【发布时间】:2020-03-15 15:49:51
【问题描述】:

我是 React Native 的新手。我在 Firebase 上获取数据,但我想获取它的 JSON 文件。我的 JSON 文件是这样的:enter image description here

如何将 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;
}

};

【问题讨论】:

    标签: javascript json react-native


    【解决方案1】:

    这是从 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

    的工作示例

    https://snack.expo.io/@asad_4561/b21f6d?session_id=snack-session-EGg1r5WPo&preview=true&platform=web&iframeId=g11cgnoglm&supportedPlatforms=ios,android,web&name=Fetch%20Example&description=Example%20usage&waitForData=true

    【讨论】:

      【解决方案2】:

      这里有一些很好的参考资料可以解决您的问题,通过阅读它们,您的问题将得到解决:

      Medium: This is very good

      RN docs

      Another Good ref

      【讨论】:

        猜你喜欢
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 2015-07-15
        • 2021-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-23
        相关资源
        最近更新 更多