Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

react-router 路由参数问题

我现在想实现这样一个路由:
/:username
/search
/about

现在的问题是:
如果请求一个用户页面是/lilei,那么路由就匹配上/:username,
如果是搜索页面/search,那么路由就匹配上/search,
现在我请求/search,可是路由匹配上了/:username,这个如何处理?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

使用next.js的动态路由就解决了,哈哈,
文件夹目录:pages/[username]就可以了,下面是页面代码,这样就可以获取用户名,并且判断是否有该用户,没有则跳转到404,这就是我想要的

import { useRouter } from "next/router";
import DefaultErrorPage from "next/error";

const Settings = () => {
  const router = useRouter();
  const { query } = router;

  if (JSON.stringify(query) != "{}") {
    if (query.username != "zhangwei") {
      return <DefaultErrorPage statusCode={404} ></DefaultErrorPage>;
    } else {
      return <div>{query.username}</div>;
    }
  } else {
    return <>Loading</>;
  }
};

export default Settings;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...