React router 链接或浏览器历史记录.push 更改地址栏中的网址,但不要从网址中包含动态参数的页面重定向



我的侧边栏中带有React-Router链接。其中一个按钮的目的是将用户重定向到他的个人资料页面,like/user/:user_id

我为该链接定义了一些逻辑,并且在几乎所有情况下都没有任何问题。它的外观:

export class SideBar extends React.Component {
    // ... some omitted code here ...
    getProfileUrlString() {
        /* Function for 'to' attribute of profile Link button in the sidebar.
         * Returns user's profile URL if he's logged in,
         * otherwise redirects him to the /login page
         */
        if (localStorage['token']) {
            return `/user/${localStorage['id']}/`
        } else {
            return '/login'
        }
    }
    render() {
        return (
        <div id="sidebar-wrapper" role="navigation">
            <ul className="sidebar-nav">
                <li><Link onlyActiveOnIndex activeStyle={{color: "#53acff"}} 
                    to="/">Home</Link></li>
                <li><Link onlyActiveOnIndex activeStyle={{color: "#53acff"}} 
                    to={this.getProfileUrlString()}>Profile</Link></li>
                {this.renderSignOutBtn()}
            </ul>
        </div>
      );
    }
}

这是我的路由器:

ReactDOM.render(
  (<Router history = {browserHistory}>
      <Route path = "/" component = {APP}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home}/>
         <Route path = "/login" component = {LoginComponent} />
         <Route path = "/registration" component = {RegistrationComponent} />
         <Route path = "/user/:user_id" component = {Profile} />
      </Route>
  </Router>),
  document.getElementById('app'));

假设我有一个帐户,ID是102,因此我的个人资料页面可在/user/102

提供

当我访问诸如'/'或"/login"之类的非动态URL,然后单击Navbar中的配置文件链接时,它可以很好地工作!它成功地将我重定向到我的个人资料。但是,当我访问其他使用URL的其他用户的页面时,例如/user/5,然后单击配置文件链接以获取什么都没有发生!除了一个奇怪的事情:地址栏中的URL从/用户/5更改为/用户/102。但是Profile的组件并没有启用,并且用户编号5的所有数据都在我面前。

我试图重新定义某些逻辑以进行OnClick事件并分配浏览史。PUSH重定向,但也存在相同的问题。我尝试了this.history.push,结果相同。

如何将其从类似页面的URL中的动态ID重定向到该页面,并具有类似的动态参数?

react:15.3.2

React-Router:2.8.1

您应该尝试在routes.js中处理身份验证检查。这样,您可以通过设置路线的onEnter支柱在组件外进行此检查。您可以在一个地方处理所有验证检查。您也不需要路径中的:user_id

// Routes.js
function requireLogin() {
  if (!localStorage['token']) {
    browserHistory.push('/login');
  }
};
<Route path="/user" component={Profile} onEnter={requireLogin} />

然后在您的SideBar组件中,只需将其重定向到/user

<li>
  <Link onlyActiveOnIndex activeStyle={{color: "#53acff"}} to="/user">Profile</Link>
</li>

然后在Profile组件中,使用componentDidMount()功能中使用localStorage['id']加载用户数据。

最新更新