反应路由器链接或browserHistory.push更改地址栏中的网址,但不要从页面中重定向动态参数在其中的网址

时间:2016-12-01 11:27:46

标签: javascript reactjs react-router

我的侧栏有react-router链接。其中一个按钮的用途是将登录用户重定向到他的个人资料页面,其中包含/ 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

当我访问非动态网址时,例如&#39; /&#39;或者&#39; / login&#39;然后单击导航栏中的配置文件链接,它完美地运行!它成功地将我重定向到我的个人资料。但是当我访问其他用户的页面时,如/ user / 5这样的url并点击Profile链接取回没有任何反应!除了一件奇怪的事情:地址栏中的url从/ user / 5更改为/ user / 102。但是个人资料的组件并没有重新呈现,用户5的所有数据都在我面前。

我尝试重新定义onClick事件的一些逻辑并分配browserHistory.push重定向,但也有同样的问题。我也尝试过this.history.push,结果相同。

如何使用类似动态参数的类似页面重定向到包含动态ID的页面?

反应:15.3.2

react-router:2.8.1

1 个答案:

答案 0 :(得分:0)

您应该尝试在routes.js中处理身份验证检查。这样,您可以通过设置Route的onEnter prop来检查组件外部。您可以在一个地方处理所有身份验证。您也不需要路径中的: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组件中,使用localStorage['id']功能中的componentDidMount()加载用户数据。