未处理的抑制(的SyntaxError):意外令牌<在JSON在位置0起反应

问题描述 投票:0回答:1

我不断收到“未处理的抑制(SyntaxError错误):意外标记<在JSON在位置0”的错误时,我尝试使用全局变量来自不同的组件,在这种情况下,当我在随机使用全局变量从Brewery.js。 JS

Brewery.js

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

Random.js

  componentDidMount() {
    fetch(window.url)
      .then(response => response.json())
      .then((data) => {
        this.setState({
          breweries: data,
        })
      })
  }
javascript reactjs
1个回答
1
投票

你说的第一个块(Brewery.js)的作品,但第二(Random.js)没有。

这当然是不良的做法创造componentDidMount一个全局变量并在另一个组件依赖于它。显然,发生了什么是第二部件之前,首先安装,所以window.urlundefined,所以你最终请求"undefined"而不是正确的网址。

首先,不要重复自己。取而代之的是,有一个单一的功能得到啤酒厂,并重新使用它:

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.jsexport default function loadBreweriesIntoState() { // ... } Brewery.jsimport loadBreweriesIntoState from "./loadBreweriesIntoState.js"; // ... componentDidMount() { loadBreweriesIntoState(this); } Random.jsimport loadBreweriesIntoState from "./loadBreweriesIntoState.js"; // ... componentDidMount() { loadBreweriesIntoState(this); }
  2. 如果你不使用的模块,把它放在你包括前两个组件脚本(开发中),并设置在你的包(用于生产)将包含在他们面前的脚本。

这两个选项适用,如果你想保留的逻辑,而不是组件,太:只是要url某种Config.js(或者一个全球性的,它创造)的出口。

© www.soinside.com 2019 - 2024. All rights reserved.