2017-02-09 140 views
0

App.js陣營-路由器:更新路由的組件上新道具

import React, { Component } from 'react'; 
import { Router, Route, browserHistory } from 'react-router'; 
import Login from './Login'; 
import Courses from './Courses'; 

class App extends Component { 
    constructor() { 
    super(); 

    this.state = { 
     username: '', 
     password: '' 
    }; 
    } 

    setCredentials = ({ username, password }) => { 
    this.setState({ 
     username, 
     password 
    }); 
    } 

    render() { 
    return (
     <Router history={browserHistory}> 
     <Route 
      path='/' 
      component={Login} 
      setCredentials={this.setCredentials} 
      /> 
     <Route 
      path='/courses' 
      component={Courses} 
      credentials={this.state} 
      /> 
     </Router> 
    ); 
    } 
} 

Login組件需要憑證從用戶,通過API調用對其進行驗證,更新App的他們狀態,然後使用this.props.router.push('/courses')重定向到Courses組件。

Courses組件應該採取在更新憑證(即App的更新的狀態)的道具,事後進行的API調用來獲取該用戶的課程。

如何在Courses組件中檢測App的狀態更新?我做錯了嗎?

回答

1

通行證道具路線的組件正確:

<Route 
     path='/' 
     component={(props) => <Login setCredentials={this.setCredentials} {...props} />} 
     /> 

和NOT :

<Route 
     path='/' 
     component={Login} 
     setCredentials={this.setCredentials} 
     /> 

Courses組件相同,您通過e XTRA道具以同樣的方式:

<Route 
     path='/courses' 
     component={(props) => <Courses credentials={this.state} {...props} />} 
     /> 

,而不是:

<Route 
     path='/courses' 
     component={Courses} 
     credentials={this.state} 
     /> 

,回答了這樣一個問題:

我如何檢測應用程序的狀態更新的課程組件內部?

因爲crendentials成爲Courses道具,其值的Appstate

+0

它的工作!謝謝你,先生! –

0

當你與課程組件從道具讀說你可以有一個生命週期掛鉤,像這樣的課程組成:

componentWillReceiveProps(nextProps) { 
    if(nextProps.isAuthenticated && this.props.credentials !== nextProps.credentials) { 
    // perform fetch for courses here 
    } 
} 
+0

不幸的是'componentWillReceiveProps'永遠不會被調用。 –

+0

@AbdelrahmanMaged新的答案將解決'componentWillReceiveProps'問題,因爲在將屬性設置爲react-router組件而不是您自己的屬性之前,將不會調用'componentWillReceiveProps'問題。 –