React router Link或browserHistory.push更改地址栏中的url,但不要从带有动态参数的页面重定向到它的url [英] React router Link or browserHistory.push change url in the address bar but don't redirect from the page with dynamic params in it's url

查看:576
本文介绍了React router Link或browserHistory.push更改地址栏中的url,但不要从带有动态参数的页面重定向到它的url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的侧栏有react-router链接。其中一个按钮的目的是将登录用户重定向到他的个人资料页面,其中包含/ user /:user_id



我为该链接定义了一些逻辑,它完美地运行几乎在所有情况下都没有任何问题。以下是它的样子:

 导出类SideBar扩展了React.Component {
// ...一些省略的代码这里...
getProfileUrlString(){
/ *侧边栏中的配置文件链接按钮的'to'属性的功能。
*如果他已登录,则返回用户的个人资料网址,
*否则将他重定向到/ login页面
* /
if(localStorage ['token']){
返回`/ user / $ {localStorage ['id']} /`
} else {
return'/ login'
}
}

render(){
return(
< div id =sidebar-wrapperrole =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(
(<路由器历史= {browserHistory}>
<路径路径=/组件= {APP}>
< IndexRoute component = {Home} />
< Route path =homecomponent = {Home} />
< Route path = / logincomponent = {LoginComponent} />
< Route path =/ registrationcomponent = {RegistrationComponent} />
< Route path =/ user /:user_idcomponent = {个人资料} />
< /路线>
< /路由器>),
document.getElementById('app'));

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



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



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



如何从具有相似动态参数的类似页面重定向到带有动态ID的页面? / p>

反应:15.3.2



react-router:2.8.1

解决方案

您应该尝试在 routes.js 中处理身份验证检查。这样,您可以通过设置Route的 onEnter prop来检查组件外部。您可以在一个地方处理所有身份验证。您还不需要路径中的:user_id

  // Routes.js 

函数requireLogin(){
if(!localStorage) ['token']){
browserHistory.push('/ login');
}
};

< Route path =/ usercomponent = {Profile} onEnter = {requireLogin} />

然后在你的 SideBar 组件中,只需重定向一直到 / user

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

然后在个人资料组件中,加载用户数据在 componentDidMount()函数中使用 localStorage ['id']


I have the sidebar with react-router Links in it. Purpose of one of the buttons is to redirect logged in user to his profile page with url like /user/:user_id

I defined some logic for that link and it works perfectly without any problems in almost all cases. Here's how it looks like:

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>
      );
    }
}

It is my router:

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'));

Let's say I have an account and id is 102 so mine profile page is available at /user/102

When I visit non-dynamic urls like '/' or '/login' and then click on the Profile Link in the navbar it works perfectly! It successfully redirects me to my profile. But when I visit page of some other user with url like /user/5 and click on Profile link to get back nothing happens! Except one strange thing: url in the address bar changes from /user/5 to /user/102. But profile's component doesn't rerender and all data of user number 5 is in front of me.

I tried to redefine some logic for onClick event and to assign browserHistory.push redirections but there is the same problem too. I tried this.history.push too with the same result.

How can I redirect to the page with dynamic ids in it's url from similar page with similar dynamic params?

React: 15.3.2

react-router: 2.8.1

解决方案

You should try handling the authentication check in your routes.js. This way you can do this check outside of the component by setting the onEnter prop of the Route. You can handle all auth checks in one place. You also don't need the :user_id in the path.

// Routes.js

function requireLogin() {
  if (!localStorage['token']) {
    browserHistory.push('/login');
  }
};

<Route path="/user" component={Profile} onEnter={requireLogin} />

Then in your SideBar component, just redirect to /user all the time.

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

Then in your Profile component, load the user data using localStorage['id'] in your componentDidMount() function.

这篇关于React router Link或browserHistory.push更改地址栏中的url,但不要从带有动态参数的页面重定向到它的url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆