javascript - 未处理的拒绝(语法错误): Unexpected token < in JSON at position 0 React

标签 javascript reactjs

每当我尝试使用来自不同组件的全局变量时(在本例中当我使用 Brewery.js 中的全局变量时),我都会不断收到“未处理的拒绝(语法错误):位置 0 处的 JSON 中的意外标记 <”错误在 Random.js 中

Brewery.js

  componentDidMount() {
    window.url = "https://api.openbrewerydb.org/breweries";
    fetch(window.url)
      .then(response => response.json())
      .then((data) => {
        this.setState({
          breweries: data,
        })
      })
  }

随机.js

  componentDidMount() {
    fetch(window.url)
      .then(response => response.json())
      .then((data) => {
        this.setState({
          breweries: data,
        })
      })
  }

最佳答案

您说过第一个 block (Brewery.js) 有效,但第二个 block (Random.js) 无效。

componentDidMount 中创建全局变量并在另一个组件中依赖它当然是不好的做法。显然,发生的情况是第二个组件在第一个组件之前安装,因此 window.urlundefined,因此您最终会请求 “undefined” 而不是正确的 URL。

首先,不要重复自己。相反,有一个获取啤酒厂的函数,并重用它:

function getBreweries() {
  return fetch(window.url)
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error " + response.status);
        });
        return response.json();
    });
}

您甚至可以让它处理设置状态:

function loadBreweriesIntoState() {
  return fetch(window.url)
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error " + response.status);
        });
        return response.json();
    })
    .then(breweries => {
        component.setState({breweries});
    })
    .catch(error => {
        component.setState({error: "Error loading the list of breweries."});
    });
}

然后,在两个组件(Random.js 和 Brewery.js)中,使用该函数而不是重复逻辑。

这让我们想到:如何使该功能可供两个组件使用?

两个答案:

  1. 如果您使用模块(我强烈推荐),请将其放入它们都使用的模块中:

    loadBreweriesIntoState.js:

    export default function loadBreweriesIntoState() {
        // ...
    }
    

    Brewery.js:

    import loadBreweriesIntoState from "./loadBreweriesIntoState.js";
    
    // ...
    
        componentDidMount() {
            loadBreweriesIntoState(this);
        }
    

    Random.js:

    import loadBreweriesIntoState from "./loadBreweriesIntoState.js";
    
    // ...
    
        componentDidMount() {
            loadBreweriesIntoState(this);
        }
    
  2. 如果您不使用模块,请将其放入您在两个组件脚本(开发中)之前包含的脚本中,并设置为将其包含在您的 bundle 中(用于生产)中。

如果您也想将逻辑保留在组件中,则这两个选项也适用:只需将 url 导出到某种 Config.js (或它创建的全局)。

关于javascript - 未处理的拒绝(语法错误): Unexpected token < in JSON at position 0 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54505620/

相关文章:

javascript - JavaScript 中的作用域是如何工作的?

javascript - 如何通过 Unobtrusive Validation JS 给出警报框或关注发生的错误

javascript - 如何将一个数组元素与其各自的下一个数组元素交换并显示输出?

javascript - 简单 <ul> <li> HTML 结构 : MegaMenu

javascript - 用 ECMAScript 重写 AngularJS 2.0?

reactjs - 后验证失败 : Path '...' is required when using react-hooks-form

reactjs - 如何在 React 中使用 api 数据填充下拉列表?

javascript - 类型错误 : Invalid attempt to destructure non-iterable instance React/Jest

javascript - 在使用 React Transition Group Component 构建轮播时,我缺少什么?

javascript - 如何从 react 表中单击表行转到另一个页面?