gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:51:35 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com