1

React-Router v.4(およびredux-saga)にアップグレードしました。あなたが見ることができるようにReact-router-dom v4 BrowseRouterが子に関数を渡す

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; 

:私の子コンポーネントは次のようになります

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

:しかし、私は、ルート内の子供に親コンテナからの通過機能に問題がある...

親ています私は関数loadGalleryGalleryコンポーネントに渡そうとしていますが、DOM内のGalleryコンポーネントはloadGallery関数をそのcに送信しないRouteコンポーネントにラップされていますヒルド。 onLoadEvent=loadGalleryHandler()がギャラリーに渡されていない明らかに

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

これのDOMを反応させるのでは次のようになります。

どうすればいいですか?

答えて

2

あなたが気づいたように、<Route>に渡された小道具はコンポーネントに渡されません。これはRouteのrender propの正確な使用例です。これに代えて

<Route path="/gallery" onLoadEvent={this.loadGalleryHandler} component={Gallery} /> 
あなたがこれを行うと、あなたが好きなあなたのコンポーネントに任意の小道具を渡すことができ

<Route path="/gallery" render={() => (
    <Gallery {...props} onLoadEvent={this.loadGalleryHandler} /> 
)} /> 
関連する問題