2017-09-12 7 views
0

Ich benutze die nächste (5.0.0-alpha.6) Version react-router-redux, die mit react-Router 4.x kompatibel ist. Ich versuche Parameter auf URL zu setzen, während ich zur nächsten Seite weiterleite.React-Router-Redux gesendet LOCATION_CHANGE zweimal, entfernen Suchwert

Jedes Mal, wenn es auf die nächste Seite bewegt. Ich erkenne, dass es @LOCATION_CHANGE 2 Mal, in the second time it removes search value aufrufen. Es funktioniert gut, wenn ich es von Tastenereignis

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}`})) 
     } 
    } 
//.... 

Griff}

Antwort

1

Ich denke, Sie sollten den Pfad in nextProps passieren.

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

Vielen Dank für Ihre Antwort, aber es scheint, wie nicht für mich arbeiten https://gyazo.com/77ca970422d4e29d6dcc418435417977 –