2017-04-13 75 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} /> 
)} />