![](/img/trans.png)
[英]Attempted import error: 'BrowseRouter' is not exported from 'react-router-dom' (imported as 'Router')
[英]React-router-dom v.4 BrowseRouter pass function to child
我剛剛升級到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
函數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()
不會傳遞給Gallery。
我該如何運作?
如您所知,傳遞給<Route>
道具不會傳遞給組件。 這是路線的render
道具的確切用例。
代替這個
<Route path="/gallery" onLoadEvent={this.loadGalleryHandler} component={Gallery} />
您可以執行此操作,然后將任何道具傳遞到所需的組件,
<Route path="/gallery" render={() => (
<Gallery {...props} onLoadEvent={this.loadGalleryHandler} />
)} />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.