React-router-dom v.4 BrowseRouter 传递函数给 child

React-router-dom v.4 BrowseRouter pass function to child

我刚刚升级到 React-Router v.4(和 redux-saga)。但是我在将函数从 parent 容器传递到路由内的 child 时遇到问题...

Parent:

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);

我的 child 组件如下所示:

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 组件,但是,在 dom 中,Gallery 组件被包裹在Route 组件不会将 loadGallery 函数发送到其 child。

这就是它在 React 中的样子 dom:

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

显然 onLoadEvent=loadGalleryHandler() 没有传递给图库。

如何让它发挥作用?

如您所见,您传递给 <Route> 的道具不会传递给您的组件。这是路线的 render 道具的确切用例。

而不是这个,

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

您可以这样做,然后将任何道具传递给您想要的组件,

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