简体   繁体   English

javascript中导入字符串中间的变量串联

[英]concatenation of the variable in the middle of the imported string in javascript

I create a special js file in which I will map all my api endpoints that I will import into my redux-saga:我创建了一个特殊的 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`,
  },
};

but my endpoint looks like this:但我的端点看起来像这样:

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}`
  ...
};

How can I do it to make it look nice and professional?我怎样才能让它看起来漂亮和专业? Does the latest js allow you to do something like this?最新的js是否允许你做这样的事情?

You could store your urls into functions, this way you could pass some parameters to fill the gaps.您可以将您的网址存储到函数中,这样您就可以传递一些参数来填补空白。

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`,
  },
};

then you call it like any other functions.然后你像任何其他函数一样调用它。

import { api } from 'utils';

export function* checkEmail({ value }) {
  const requestURL = `${api.users.checkEmail(value)}`
  ...
};

I've also replace your string concatenation in your string template because i'm not sure that's what you wanted.我还替换了字符串模板中的字符串连接,因为我不确定这就是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM