每当我尝试使用来自不同组件的全局变量时(在本例中当我使用 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.url
是 undefined
,因此您最终会请求 “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)中,使用该函数而不是重复逻辑。
这让我们想到:如何使该功能可供两个组件使用?
两个答案:
如果您使用模块(我强烈推荐),请将其放入它们都使用的模块中:
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); }
如果您不使用模块,请将其放入您在两个组件脚本(开发中)之前包含的脚本中,并设置为将其包含在您的 bundle 中(用于生产)中。
如果您也想将逻辑保留在组件中,则这两个选项也适用:只需将 url
导出到某种 Config.js
(或它创建的全局)。
关于javascript - 未处理的拒绝(语法错误): Unexpected token < in JSON at position 0 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54505620/