【问题标题】:react-router root onChange to replace path infinitereact-router root onChange 替换路径无限
【发布时间】:2016-11-23 07:32:32
【问题描述】:

似乎如果我在根 onEnter 或 onChange 钩子中更改路径,则 url 将无限更改。但是,如果我更改子路线中的路径,它将起作用。实际上我想在一个地方处理身份验证,否则每个子路由都应该处理相同的逻辑。

{
    path: '/',
    onChange: function(prevState, nextState, replace, callback) { 
        if(!logined) {
            replace('login');
        }
    },
    childRoutes: [
        ....
    ]
}

【问题讨论】:

    标签: react-router react-router-redux react-router-component


    【解决方案1】:

    它无限变化,因为onChange 调用replace

    试试

     onChange: function(prevState, {location:{pathname:next}}, replace)=> {
          if(!logined && next !== '/login') {
              replace('/login');
          }
     }
    

    也可以在一个地方处理身份验证,您可以使用 HOC,类似的东西

    const CheckAuth = (isLogined, redirectPath) => Component => 
    class CheckAuth extends React.Component {
        componentWillUpdate(nextProps, nextState){
            //Check auth on change
            this.checkAuth(nextProps);
        }
        componentWillMount(){
            //Check auth on enter
            this.checkAuth(this.props);
        }
        checkAuth({location}){
            if(!isLogined && location.pathname!==redirectPath) {
                browserHistory.replace(redirectPath);
            }
        }
        render(){
            return (<Component {...this.props}/>);
        }
    };
    

    和应用组件

    class App extends React.Component { ... }
    export default CheckAuth(isLogined,'/login')(App);
    

    另外,redux-auth-wrapper 也有办法

    【讨论】:

      猜你喜欢
      • 2017-03-28
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 2017-01-14
      • 2022-07-12
      • 2017-09-04
      • 1970-01-01
      • 2018-05-07
      相关资源
      最近更新 更多