2017-02-09 8 views
0

App.jsリアクト-ルーターを:新しい小道具のUpdateルートのコンポーネント

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コンポーネントは、彼らとアップデートAppの状態、APIの呼び出しを介してそれらを検証し、ユーザーからの資格情報を取り込み、 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

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

はなく:

がどのように私はコースのコンポーネント内のAppの状態に更新を検出することができます質問に答える

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

同じようにエクストラ-小道具? crendentialsので

Coursesの支柱とAppのその値stateなります。

+0

それは働いた!ありがとうございます! –

0

は、あなたはとてもコースコンポーネントのようにライフサイクルフックを持つことができます:正しくルートのコンポーネントに

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

残念ながら、 'componentWillReceiveProps'は呼び出されません。 –

+0

@AbdelrahmanMaged新しい回答は、あなたが自分自身ではなく反応ルータのコンポーネントにプロパティを設定する前に、 'componentWillReceiveProps'が呼び出されることはないという問題を解決します。 –

関連する問題