将模板字符串定义为 const 以便稍后评估
Define template strings as const to evaluate later
有没有办法完成这样的事情:
const API_URL = `https://api.my-data-provider.com/items/${id}`
// [...]
// and later on or in another file, use it with something like
const result = await fetch(API_URL(id)) // or API_URL.apply(id), API_URL.apply({ id: 23}), etc...
我想将模板文字保存在常量/配置文件中,以备后用
或者是否有任何其他标准或公认的方法来做这种事情?
你可以为此使用一个函数:
const generateApiUrl = (id) => `https://api.my-data-provider.com/items/${id}`;
const result = await fetch(generateApiUrl(id))
有没有办法完成这样的事情:
const API_URL = `https://api.my-data-provider.com/items/${id}`
// [...]
// and later on or in another file, use it with something like
const result = await fetch(API_URL(id)) // or API_URL.apply(id), API_URL.apply({ id: 23}), etc...
我想将模板文字保存在常量/配置文件中,以备后用
或者是否有任何其他标准或公认的方法来做这种事情?
你可以为此使用一个函数:
const generateApiUrl = (id) => `https://api.my-data-provider.com/items/${id}`;
const result = await fetch(generateApiUrl(id))