我的api提取调用使用相同的标头,而不是为每个api调用函数重复变量,我可以将这些变量放在一个位置,然后调用这些变量吗?我试过将它们放入函数中,然后调用该函数,但是反应抱怨变量丢失。我正在使用一个类组件,并且我要重复引用 parsed 和 headersAPI 变量,理想情况下,我希望将它们放在一个位置。
componentDidMount() {
this.getUserProfile();
this.searchBands();
}
getUserProfile() {
let parsed = new URLSearchParams(window.location.search).get(
"access_token"
);
parsed = { token: parsed };
console.log(parsed.token);
let headersAPI = {
headers: { Authorization: "Bearer " + parsed.token }
};
fetch(`https://api.spotify.com/v1/me`, headersAPI)
.then(response => response.json())
.then(data =>
this.setState({
userName: data.display_name,
log: console.log(data)
})
)
.catch(error =>
this.setState({
log: console.error("Error:", error),
errorApi: true
})
);
}
searchBands(name) {
let parsed = new URLSearchParams(window.location.search).get(
"access_token"
);
parsed = { token: parsed };
console.log(parsed.token);
let headersAPI = {
headers: { Authorization: "Bearer " + parsed.token }
};
let searchName = this.state.searchName === "" ? "The Cure" : name;
//search band
fetch(
`https://api.spotify.com/v1/search?q=${searchName}&type=artist`,
headersAPI
)
.then(response => response.json())
.then(data =>
this.setState({
artistName: data.artists.items[0],
log: console.log(data),
image: data.artists.items[0].images[0].url
})
)
.catch(error =>
this.setState({
log: console.error("Error:", error),
errorApi: true
})
);
}
答案 0 :(得分:1)
我只是将变量放置在类声明之外,然后在api调用函数中调用它们,似乎可以正常工作。
const parsed = new URLSearchParams(window.location.search).get("access_token");
const headersAPI = {
headers: { Authorization: "Bearer " + parsed }
};
class App extends Component {..}