如何在React-Router的单个路径中匹配相似的路由条件?

时间:2019-02-01 17:39:21

标签: reactjs react-router

我有一个名为Details的组件,其路由如下所示:

let words = ["the","best","world"];
let words2 = ["the","best","world","apple"];
var myString = 'Stackoverflow is the best site for all developers in the world';
function checkWords(str,words){
  for(let word of words){
    //if the word in words arr doesnot exist is str it will return false
    if(!str.includes(word)) return false
  }
  //if false is not return in loop it means all words exist is str so return true 
  return true;
}
console.log(checkWords(myString,words));
console.log(checkWords(myString,words2));

现在,如果用户尝试仅访问“ / details”路由,我想将其重定向到外部URL,例如“ https://www.google.com”。目前,我被行后加入以上下列正确的做const appRoutes=[ { path: "/details/:id", component: Details } ]

appRoutes

是否有一种更好的方法可以在一行而不是两行中进行操作,这样我就不必像在这里那样分别指定`{ path: "/details", component: () => window.location.assign("https://www.google.com") }` /details的大小写?这里的预期行为是,如果路由为details/:id,则呈现details/:id组件;如果路由仅为Details,则将其发送到外部URL。

1 个答案:

答案 0 :(得分:2)

根据您的想法的定义,这些是分开的路线。因此,最好使用单独的route语句来定义它们。如果有的话,这只会使您的代码更具声明性,并且对其他读者来说更清晰。

我建议您将exact: true传递到"/details"路线,并在您的"/details/:id"路线之前 放置。在定义基于参数的路由之前,React Router可以更轻松地确定要显示的路由。

希望这会有所帮助!