繁体   English   中英

使用 Promise React 从模块导出文件中获取 API

[英]Fetching API from Module Export File with Promises React

我想获取从模块文件 data.js 导出的 API

我收到此错误“err SyntaxError: Unexpected token < in JSON at position 0”

下面的文件包含 API 模块

 /**
 * @typedef {object} PropertyType
 * @property {string} label - The text to display
 * @property {string} value - The enum value assigned
 */

 /**
 * Retrieve a list of all available property types.
 *
 * @returns {Promise<{ propertyTypes: PropertyType[] }>}
 */

async function getAvailablePropertyTypes() {
  await wait(randomInteger(500));

  return {
    propertyTypes: [
      { label: 'Semi-detached', value: 'semi-detached' },
      { label: 'Detached house', value: 'detached' },
      { label: 'Terraced house', value: 'terraced' },
      { label: 'Flat', value: 'flat' },
    ]
  };
}

export {getAvailablePropertyTypes};

以下文件包含导入的 API app.js

我想我在这一行没有正确获取 const response = await fetch(getAvailablePropertyTypes.propertyTypes)

如何从此 function getAvailablePropertyTypes.propertyTypes 获取?

import  {getAvailablePropertyTypes} from './properties'
import { useEffect } from 'react'

function App() {

useEffect( async () => {
      const response = await fetch(getAvailablePropertyTypes.propertyTypes)
      const data = await response.json()
      .then(res => {
        console.log('res', res)
      })
      .catch(err => {
        console.log('err', err)
      })
    }, [])
    
    return (
    <div className="App">
    </div>
  );
}

getAvailablePropertyTypes是 function。 它没有propertyTypes属性,所以你会得到undefined

undefined不是 URL 对任何有用的东西,所以当你向它发出网络请求时,你会得到一个错误页面。 错误页面不是 JSON,因此是错误消息。

此代码附近的任何地方都没有 URL。 涉及fetch根本没有意义。

fetch对于从实现为 web 服务的 API 获取数据很有用。 它不会帮助您处理其他类型的 API,包括这个只是处理内部数据的一些函数。

所以让我们 go 回到开始,看看你有什么。


getAvailablePropertyTypes是 function。 所以叫吧。

const ret_value = getAvailablePropertyTypes();

它是async的,所以它返回一个 promise,所以等待它。

const data = await ret_value;

promise 的解析值是一个 object,它确实有一个propertyTypes值。 所以提取它。

const { propertyTypes } = data;

现在这是一个数组,您可以随心所欲地做任何事情

console.log(propertyTypes);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM