javascript - 如何将switch语句中的模板字符串与js匹配?

标签 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。

我该如何评估?

最佳答案

我的猜测是 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');
  }
});

关于javascript - 如何将switch语句中的模板字符串与js匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56927391/

相关文章:

javascript - d3.js - 鼠标悬停事件在 svg 组上无法正常工作

javascript - 按索引切片数组并插入空数组

javascript - 在 React 中切换语言而不使用外部库

javascript - 从另一个模块导入 PropType 值会导致未定义

c++ - 按字典顺序打印给定字符串的所有字母组合的算法

javascript - iOS 双指缩放 - 现在无法通过视口(viewport)禁用

javascript - 带有边框/周边的按钮作为加载器?

reactjs - 无法获取显示新页面的链接

java - 如何在 JSTL/JSP 的循环中连接字符串?

c# - 我如何在 C# 中将数据从字符串转换为长