[英]concatenation of the variable in the middle of the imported string in javascript
我創建了一個特殊的 js 文件,在其中我將 map 我所有的 api 端點導入到我的 redux-saga 中:
export const API_BASE_URL = 'https://localhost:3000/api';
export const USERS = '/Users';
export default {
users: {
example: `${API_BASE_URL}${USERS}/example`,
checkEmail: `${API_BASE_URL}${USERS}${HERE_I_NEED_MY_VARIABLE}/checkEmail`,
},
};
但我的端點看起來像這樣:
import { api } from 'utils';
export function* checkEmail({ value }) {
const requestURL = `https://localhost:3000/api/Users/${value}/checkEmail`;
// I would like to do this: (pseudocode) const requestURL = `${api.users.checkEmail} + ${value}`
...
};
我怎樣才能讓它看起來漂亮和專業? 最新的js是否允許你做這樣的事情?
您可以將您的網址存儲到函數中,這樣您就可以傳遞一些參數來填補空白。
export const API_BASE_URL = 'https://localhost:3000/api';
export const USERS = '/Users';
export default {
users: {
example: () => `${API_BASE_URL}${USERS}/example`,
checkEmail: (variable) => `${API_BASE_URL}${USERS}/${variable}/checkEmail`,
},
};
然后你像任何其他函數一樣調用它。
import { api } from 'utils';
export function* checkEmail({ value }) {
const requestURL = `${api.users.checkEmail(value)}`
...
};
我還替換了字符串模板中的字符串連接,因為我不確定這就是你想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.