2017-04-18 81 views
9

我需要將道具傳遞給使用路由器的組件。 這裏是我的代碼:React react-router-dom將道具傳遞給組件

import React, { Component, PropTypes } from 'react'; 
import { connect } from 'react-redux'; 
import AppBarTop from './appbar/AppBarTop'; 

import Login from '../pages/login/Login'; 
import {BrowserRouter as Router, Route} from 'react-router-dom'; 


class App extends Component { 

    render() { 

     const { isAuthenticated } = this.props; 

     return (
      <Router> 
       <div> 
        <AppBarTop isAuthenticated={isAuthenticated} /> 
        <div className="content"> 
         <Route path="/login" isAuthenticated={isAuthenticated} component={Login} /> 
        </div> 
       </div> 
      </Router> 
     ); 
    } 
} 

正如你所看到的,我isAuthenticated想傳遞給登錄組件的道具。

class Login extends Component { 

    constructor(props) { 
     super(props); 
     console.log(props); 
    } 

    render() { 
     return (
      <LoginForm /> 
     ); 
    } 

} 

export default connect(null) (Login); 

當我登錄的道具isAuthenticated道具是不存在的。我做錯了什麼?我如何正確傳遞道具? 我遵循文檔和其他討論。從我的理解,它應該工作。 的版本反應路由器反應路由器-DOM4.0.0

回答

26

通這樣的:

<Route 
    path="/login" 
    render={(props) => <Login {...props} isAuthenticated={isAuthenticated}/>} 
/> 

應該在登錄組件可通過this.props.isAuthenticated

{...props}原因:

如果我們不寫這則只有isAuthenticated將得到傳遞給登錄組件,該路由器傳遞到組件的所有其它值,將無法使用內登錄組件。當我們編寫{...props}時,我們將傳遞所有值與一個額外的值。

而不是使用component與路由器使用render方法。

DOC

Component

當您使用組件(而不是渲染或子女,下同)的 路由器使用React.createElement創建從給出的 新元素做出反應零件。這意味着,如果您爲 組件屬性提供了內聯函數,則每個渲染都會創建一個新組件。 這會導致現有組件卸載和新的組件安裝,而不是僅更新現有組件。 使用內聯函數進行內聯渲染時,請使用渲染。

Render

這使得便利的內嵌式渲染和包裝不 不需要重新掛載。

相關問題