阵营-路由器:更新路由的组件上新道具

问题描述:

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的状态更新?我做错了吗?

通行证道具路线的组件正确:

<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

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

当你与课程组件从道具读说你可以有一个生命周期挂钩,像这样的课程组成:

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

不幸的是'componentWillReceiveProps'永远不会被调用。 –

+0

@AbdelrahmanMaged新的答案将解决'componentWillReceiveProps'问题,因为在将属性设置为react-router组件而不是您自己的属性之前,将不会调用'componentWillReceiveProps'问题。 –