2017-01-17 86 views
0

我的反應應用程序中有3頁。登錄頁面,主頁和視頻頁面。路由器沒有導航到下一頁,但url更改

問題:單擊登錄按鈕時,它會成功發出POST請求,但不會導航到下一頁。當點擊登錄按鈕時,網址將變爲所需路線,但視圖不會更改。

試過:1)我嘗試使用這兩個東西:this.context.router.push('/ app'),但它給了我錯誤說未捕獲TypeError:無法讀取未定義的屬性'路由器' 2)我嘗試使用browserHistory.push('/ app'),但改變了網址,而不是視圖。

function getRoutes(store) { 

    return (
     <Router history={browserHistory}> 
      <Route path="/" component={LoginPage}/> 
      <Route path='app' component={App}> 
       <IndexRoute component={Home}/> 
       <Route> 
        <Route path='/video-screen' component={VideoScreen}/> 
        <Redirect from='*' to='/'/> 
       </Route> 
      </Route> 
     </Router> 
    ) 
} 
export default getRoutes; 

以下是我的index.js文件,它是使用上面的路由對Root進行渲染的入口點。

window.Promise = Promise; 
window.$ = window.jQuery = $; 
injectTapEventPlugin(); 

var browserHistory = useRouterHistory(createHistory)({ 
    queryKey: false, 
    basename: '/' 
}); 

var initialState = window.INITIAL_STATE || {}; 

var store = configureStore(initialState, browserHistory); 
var routes = getRoutes(store); 
var history = syncHistoryWithStore(browserHistory, store, { 
    selectLocationState: (state) => state.router 
}); 

const ROOT_CONTAINER = document.getElementById('root'); 
const onRenderComplete =()=> { 
    console.timeEnd('render'); 
} 

if (__DEV__){ 
    window._STORE = store; 
    window.React = React; 
    window.ReactDOM = ReactDOM; 
} 
window.localStorage.debug = 'tessact:*' 
window._History = history 

let muiTheme = getMuiTheme(theme); 

console.time('render'); 
match({ history, routes }, (error, redirectLocation, renderProps) => { 
    ReactDOM.render(
     <MuiThemeProvider muiTheme={muiTheme}> 
      <Root store={store}> 
       <WithStylesContext onInsertCss={styles=> styles._insertCss()}> 
        <Router {...renderProps} /> 
       </WithStylesContext> 
      </Root> 
     </MuiThemeProvider>, 
     ROOT_CONTAINER, 
     onRenderComplete 
    ) 
}); 

這是我的登錄頁面

export default class LogInComponent extends Component { 
    handleLoginButtonClick() { 
     var settings = { 
      "async": true, 
      "crossDomain": true, 
      "url": "https://trigger-backend.appspot.com/auth/login/", 
      "method": "POST", 
      "credentials": 'include', 
      "headers": { 
       "content-type": "application/x-www-form-urlencoded", 
      }, 
      "data": { 
       "password": "apurv", 
       "username": "Apurv" 
      }, 
      success: function(data, textStatus, jQxhr){ 
       alert("success"); 
      }, 
     } 

     $.ajax(settings).done(function (response) { 
      alert(response.auth_token); 
      console.log('check'); 
      this.context.router.push('/app') 
     }); 

    } 


    render(){ 
     return (
      <div className="LoginPage"> 
       <div className="login-page"> 
        <div className="form"> 
         <form className="login-form"> 
          <input id="username" type="username" placeholder="username"/> 
          <input id="password" type="password" placeholder="password"/> 
          <p className="message">Not registered? <a href="#">Request Username and Password</a></p> 
         </form> 
         <button onClick={this.handleLoginButtonClick.bind(this)}>login</button> 
        </div> 
       </div> 
       <img className="Logo_Tessact_White" src="./dev/js/images/TESSACT_logo_white.png"/> 
      </div> 
     ); 
    } 
} 

回答

2

第一個問題在這裏

$.ajax(settings).done(function (response) { 
     alert(response.auth_token); 
     console.log('check'); 
     this.context.router.push('/app') 
}); 

this不引用組件了,因爲它是在不同的範圍。使用arrow function的,而不是爲了重用組件的範圍

$.ajax(settings).done((response) => { // arrow function 
    alert(response.auth_token); 
    console.log('check'); 
    this.context.router.push('/app') 
}); 

No binding of this

Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.)

Arrow功能,而不是被稱爲在定義它的上下文(在這種情況下 - 你的組件)

另一個問題是這裏

LogInComponent.contextTypes = { 
    router: React.PropTypes.func.isRequired 
}; 

缺失,請添加它。


另外,根據反應路由器的版本,您可能無法正確調用API,看看這個answer更多。

+0

刪除後綁定它說無法讀取null的屬性'上下文' – ApurvG

+0

你使用哪個版本的react-router? – lustoykov

+0

綁定是正確的,離開它 – lustoykov