【问题标题】:How to match a template string in switch statement with js?如何将switch语句中的模板字符串与js匹配?
【发布时间】:2019-11-17 12:35:02
【问题描述】:

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

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。

我该如何评估?

【问题讨论】:

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


【解决方案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');
  }
});

【讨论】:

    【解决方案2】:

    在这里工作正常

    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'))

    【讨论】:

      猜你喜欢
      • 2018-10-02
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 2023-02-20
      • 1970-01-01
      相关资源
      最近更新 更多