1

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

家长:

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;

如您所见,我试图将函数传递loadGalleryGallery组件,但是,在 dom 中,Gallery组件被包装在一个Route不会将loadGallery函数发送给其子组件的组件中。

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

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

显然,onLoadEvent=loadGalleryHandler()没有传递给画廊。

我如何使它工作?

4

1 回答 1

2

正如您所注意到的,您传递给的道具<Route>不会传递给您的组件。这是 Routerender道具的确切用例。

取而代之的是,

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

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

<Route path="/gallery" render={() => (
  <Gallery {...props} onLoadEvent={this.loadGalleryHandler} />
)} />
于 2017-04-13T07:29:39.573 回答