我可以将动态值传递给 ES6 的模板文字吗?
Can I pass dynamic values to ES6's Template Literals?
getSelectedCityId() {
let citiName
citiId;
axiosInstance
.get("/api/cities")
.then(response => {
if (response.status === 200 && response.data) {
citiName = this.state.city;
citiId = this.state.city.city_id;
}
})
.catch(error => {});
let url = `/api/${citiName}/${citiId}/schools/`;
axiosInstance
.get(url)
.then(response => {
})
.catch(error => {
console.log(error);
});
}
当我点击 API 调用时,url 显示:
localhost:9000/api/undefined/undefined/schools/
我正在尝试将从第一个 API 调用中获得的数据作为参数传递给第二个 API.My 点是,为什么模板文字抛出 undefined ?我们不允许通过模板文字传递动态数据吗?
由于获取/api/cities
数据是异步操作,需要等待结果。仅用于概念验证:
getSelectedCityId()
{
let citiName
citiId;
axiosInstance
.get("/api/cities")
.then(response => {
if (response.status === 200 && response.data) {
citiName = this.state.city;
citiId = this.state.city.city_id;
return `/api/${citiName}/${citiId}/schools/`;
}
return null;
})
.then(url => {
if(url) { // the data from previous then
axiosInstance.get(url) //.then().catch()
}
});
}
getSelectedCityId() {
let citiName
citiId;
axiosInstance
.get("/api/cities")
.then(response => {
if (response.status === 200 && response.data) {
citiName = this.state.city;
citiId = this.state.city.city_id;
this.getSelectedCityIdStepTwo(`/api/${citiName}/${citiId}/schools/`);
}
})
.catch(error => {});
}
getSelectedCityIdStepTwo(url) {
axiosInstance
.get(url)
.then(response => {
})
.catch(error => {
console.log(error);
});
}
这将确保在第一个 AXIOS 调用完成并且有一个有效的 URL 可以通过之前不会进行第二个 AXIOS 调用。
getSelectedCityId() {
let citiName
citiId;
axiosInstance
.get("/api/cities")
.then(response => {
if (response.status === 200 && response.data) {
citiName = this.state.city;
citiId = this.state.city.city_id;
}
})
.catch(error => {});
let url = `/api/${citiName}/${citiId}/schools/`;
axiosInstance
.get(url)
.then(response => {
})
.catch(error => {
console.log(error);
});
}
当我点击 API 调用时,url 显示:
localhost:9000/api/undefined/undefined/schools/
我正在尝试将从第一个 API 调用中获得的数据作为参数传递给第二个 API.My 点是,为什么模板文字抛出 undefined ?我们不允许通过模板文字传递动态数据吗?
由于获取/api/cities
数据是异步操作,需要等待结果。仅用于概念验证:
getSelectedCityId()
{
let citiName
citiId;
axiosInstance
.get("/api/cities")
.then(response => {
if (response.status === 200 && response.data) {
citiName = this.state.city;
citiId = this.state.city.city_id;
return `/api/${citiName}/${citiId}/schools/`;
}
return null;
})
.then(url => {
if(url) { // the data from previous then
axiosInstance.get(url) //.then().catch()
}
});
}
getSelectedCityId() {
let citiName
citiId;
axiosInstance
.get("/api/cities")
.then(response => {
if (response.status === 200 && response.data) {
citiName = this.state.city;
citiId = this.state.city.city_id;
this.getSelectedCityIdStepTwo(`/api/${citiName}/${citiId}/schools/`);
}
})
.catch(error => {});
}
getSelectedCityIdStepTwo(url) {
axiosInstance
.get(url)
.then(response => {
})
.catch(error => {
console.log(error);
});
}
这将确保在第一个 AXIOS 调用完成并且有一个有效的 URL 可以通过之前不会进行第二个 AXIOS 调用。