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()
不傳遞到畫廊。
如何讓它工作?