2017-09-12 5 views
0

J'utilise la version suivante (5.0.0-alpha.6) react-router-redux qui est compatible avec react-router 4.x. J'essaye de placer le paramètre sur l'URL tout en redirigeant vers la page suivante.React-Router-Redux envoyé deux fois LOCATION_CHANGE, supprimer la valeur de recherche

Chaque fois qu'il passe à la page suivante. Je réalise qu'il s'appelle @LOCATION_CHANGE 2 fois, in the second time it removes search value. Il fonctionne très bien si je débrouille de l'événement bouton

import { requireAuth } from '../components/AuthenticatedComponent' 
import createHistory from 'history/createBrowserHistory' 

const history = createHistory() 

return (
    <ConnectedRouter history={history}> 
     <div className="container"> 
     <Header /> 
     <Switch> 
      <Route exact path="/" component={Home} /> 
      <Route path="/about" component={requireAuth(About)} /> 
      <Route path="/login" component={Login} /> 
      <Route component={NotFound} /> 
     </Switch> 
     </div> 
    </ConnectedRouter> 
) 

AuthenticatedComponent.js

import { push } from 'react-router-redux' 

export function requireAuth(Component) { 

class AuthenticatedComponent extends React.Component { 

    componentWillMount() { 
     this.checkAuth(this.props.isAuthenticated); 
    } 

    componentWillReceiveProps(nextProps) { 
     this.checkAuth(nextProps.isAuthenticated); 
    } 

    checkAuth(isAuthenticated) { 
     if (!isAuthenticated) { 
      let redirectAfterLogin = this.props.location.pathname; 
      this.props.dispatch(push({pathname: "/login", search:`?redirect=${redirectAfterLogin}`})) 
     } 
    } 
//.... 

}

Répondre

1

Je pense que vous devriez passer le chemin dans nextProps.

class AuthenticatedComponent extends React.Component { 

//... 

componentWillReceiveProps(nextProps) { 
    this.checkAuth(nextProps.isAuthenticated); // <--- call checkAuth 
} 

checkAuth(isAuthenticated) { 
    if (!isAuthenticated) { // <-- isAuthenticated is in nextProps 

     // this.props.location.pathame is not in nextProps 
     let redirectAfterLogin = this.props.location.pathname; 
     this.props.dispatch(push({pathname: "/login", search:`?redirect=${redirectAfterLogin}`})) 
    } 
} 

//... 

class AuthenticatedComponent extends React.Component { 

componentWillMount() { 
    this.checkAuth(this.props); 
} 

componentWillReceiveProps(nextProps) { 
    this.checkAuth(nextProps); // <--- call checkAuth 
} 

checkAuth({isAuthenticated, location, dispatch}) { 
    if (!isAuthenticated) { 
     let redirectAfterLogin = location.pathname; 
     dispatch(push({pathname: "/login", search:`?redirect=${redirectAfterLogin}`})) 
    } 
} 

//... 
+0

Merci pour votre réponse, mais il semble que ne pas fonctionner pour moi https://gyazo.com/77ca970422d4e29d6dcc418435417977 –