我刚刚升级到 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;
如您所见,我试图将函数传递loadGallery
给Gallery
组件,但是,在 dom 中,Gallery
组件被包装在一个Route
不会将loadGallery
函数发送给其子组件的组件中。
这是它在 React 的 dom 中的样子:
<Route path="/gallery" onLoadEvent=loadGalleryHandler() component=Gallery()>
<Gallery match={...somestuff...} location={...somestuff...} history={...somestuff...}>...</Gallery>
</Route>
显然,onLoadEvent=loadGalleryHandler()
没有传递给画廊。
我如何使它工作?