如何在js的switch语句中匹配模板字符串?

时间:2019-07-08 01:32:37

标签: javascript reactjs string switch-statement template-strings

我有一个函数可以返回依赖于窗口路径名的组件。

getComponentByPathname = (pathname) => {
    switch(patname){
      case "/view1": return <ViewOneComponent>;
      case "/view2": return <ViewTwoComponent>;
}

但是当我尝试评估具有一个id的模板字符串时,问题就开始了

getComponentByPathname = (pathname) => {
    switch(pathname){
      case "/view1": return <ViewOneComponent>;
      case "/view2": return <ViewTwoComponent>;
      case `/view3/${getId()}`: return <ViewThreeComponent>;

}

仅适用于前两种情况。为什么? 另外,我再次尝试。在这种情况下,在第三种情况下,我会在字面上直接粘贴带有ID的字符串,如下所示:

case "view3/1234567": return <ViewThreeComponent>;

工作。但是问题是我无法对字符串中的ID进行硬编码。

我该如何评估?

2 个答案:

答案 0 :(得分:1)

在这里工作正常

function getId() {
  return 1234567
}

function test(pathname) {
  switch (pathname) {
    case '/view1':
      return 'ViewOneComponent'
    case '/view2':
      return 'ViewTwoComponent'
    case `/view3/${getId()}`:
      return 'ViewThreeComponent'
    default:
      return 'fail'
  }
}

console.log(test('/view3/1234567'))

答案 1 :(得分:1)

我的猜测是getId()返回的值与您期望的值不同。我会尝试以下方法,使getId()在计算时返回期望值

getComponentByPathname = pathname => {
  const case3 = `/view3/${getId()}`;
  console.log(`case3 = ${case3}`);
  console.log(`pathname = ${pathname}`);

  switch (pathname) {
    case '/view1':
      return <ViewOneComponent>;
    case '/view2':
      return <ViewTwoComponent>;
    case case3:
      return <ViewThreeComponent>;
  }
};

但是,如果您只需要根据路径决定要渲染的组件,那么类似这样的方法可能更合适

const examplePaths = ['view1/', 'view2/', 'view3/', 'view3/1241232', 'view3/8721873216', 'view4/', 'vi/ew1', ''];

const mapper = {
  view1: 'ViewOneComponent',
  view2: 'ViewTwoComponent',
  view3: 'ViewThreeComponent'
};

examplePaths.forEach(ent => {
  const splitPaths = ent.split('/');

  const mapped = mapper[splitPaths[0]];
  if (mapped) {
    console.log(mapped);
  } else {
    console.log('Path not supported');
  }
});