2017-04-13 74 views
1

我剛剛升級到React-Router v.4(和redux-saga)。但我有從父容器傳遞功能,以孩子的路線內的問題...React-router-dom v.4 BrowseRouter傳遞函數給孩子

家長:

import React, { Component } from 'react'; 
import { bindActionCreators } from 'redux'; 
import { connect } from 'react-redux'; 
import { BrowserRouter as Router, Route, NavLink } from 'react-router-dom'; 

import { fetchGalleryImages } from './business_logic/modules/gallery' 

import logo from './assets/images/saga-logo.png'; 
import Gallery from './components/Gallery'; 

function mapStateToProps(state) { 
    return { galleryImages: state.galleryImages }; 
} 
function mapDispatchToProps(dispatch) { 
    return { actions: bindActionCreators({ fetchGalleryImages }, dispatch) }; 
} 

class App extends Component { 
    constructor(props) { 
     super(props); 
     this.loadGallery = props.actions.fetchGalleryImages.bind(this); 
    } 

    loadGalleryHandler() { 
     this.loadGallery(); 
    } 

    render() { 
     return (
      <div className="App"> 
       <img src={logo} className="logo" alt="logo" /> 
       <h1>Welcome to Redux-Saga</h1> 
       <section className="content"> 
        <p>This is an exersize in using react together with Redux-saga.</p> 

        <Router> 
         <div> 
          <nav className="main"> 
           <NavLink activeClassName="selected" exact to="/" >Home</NavLink> 
           <NavLink activeClassName="selected" to="/gallery">Gallery</NavLink> 
          </nav> 

          <Route path="/gallery" onLoadEvent={this.loadGalleryHandler} component={Gallery} /> 
         </div> 
        </Router> 
       </section> 
      </div> 
     ); 
    } 
} 

export default connect(mapStateToProps, mapDispatchToProps)(App); 

我的孩子組成是這樣的:

import React, { Component } from 'react'; 

class Gallery extends Component { 

    componentDidMount() { 
     this.props.onLoadEvent(); 
    } 

    render() { 
     return (
      <div className="Gallery"> 
       <h2>Gallery</h2> 
      </div> 
     ); 
    } 
} 

export default Gallery; 

正如你所看到的我試圖將功能loadGallery傳遞給Gallery組件,但是,在該組件中,Gallery組件被封裝在Route組件中,該組件不會將loadGallery函數發送到其c希爾德。

這就是它看起來像在陣營的DOM:

<Route path="/gallery" onLoadEvent=loadGalleryHandler() component=Gallery()> 
    <Gallery match={...somestuff...} location={...somestuff...} history={...somestuff...}>...</Gallery> 
</Route> 

顯然onLoadEvent=loadGalleryHandler()不傳遞到畫廊。

如何讓它工作?

回答

2

如您所見,您傳遞給<Route>的道具不會傳遞給您的組件。這是Route的render道具的確切用例。

取而代之的是,

<Route path="/gallery" onLoadEvent={this.loadGalleryHandler} component={Gallery} /> 

你可以做到這一點,然後通過任何道具,你的組件,你想,

<Route path="/gallery" render={() => (
    <Gallery {...props} onLoadEvent={this.loadGalleryHandler} /> 
)} />