首页 > 解决方案 > 使用参数将路由器路由反应到错误的组件

问题描述

我正在尝试使用react-router路由 toa。用户个人资料页面。

我的用户行组件如下:

render() {

        return (
            <div className="userrow">
                <div className="userrow-username">
                    {this.props.name}
                </div>
                <div>
                    <Link to={`/profile/${this.props.username}`} style={{ textDecoration: 'none' }}>
                        <Button variant="outlined" color="primary" size="small">
                            View Profile
                        </Button>
                    </Link>
                </div>
            </div>
        )
    }

路由器:

public render() {

    return (this.state.loading === true) ? <h1>Loading</h1> : (

      <BrowserRouter>

        <div>
          <HeaderNav />

          <Switch>
            <Route exact={true} path={routes.LANDING} component={LandingPage} />
            <Route exact={true} path={routes.SIGN_UP} component={SignUp} />
            <Route exact={true} path={routes.LOGIN} component={Login} />
            <Route exact={true} path={routes.PASSWORD_FORGET} component={PasswordForget} />
            <Route path={routes.USER} component={UserList} />
            <Route path={routes.PROJECT} component={Project} projectName='Nakul' />
            <Route path={routes.HOME} component={Home} />
            <Route exact={true} path="/profile/:username" component={UserProfile} />
          </Switch>
        </div>
      </BrowserRouter>

    );
  }

我还有一些受保护的路由,我已将它们作为消费者添加到 firebase auth。如有必要,我可以共享代码,但我不认为这是这里的问题。

问题是,当我路由到http://localhost:3000/profile/hellonakul我被重定向到home哪个是/path 。

相反,我应该被路由到我的UserProfile组件,这没有发生。

编辑:路线:

export const SIGN_UP = "/signup";
export const LOGIN = "/login";
export const LANDING = "/landing";
export const HOME = "/";
export const ACCOUNT = "/account";
export const PASSWORD_FORGET = "/password_forget";
export const PROJECT = "/project";
export const USER = "/user";

标签: reactjstypescriptroutesreact-router

解决方案


我想 Home 路线也必须exact={true}如此。

编辑:我认为在你的情况下,只有 Home 路线需要一个exact={true}属性。该属性用于解决相似路由之间的冲突。


推荐阅读