React Router Pass Param to Component

后端 未结 10 1226
南方客
南方客 2020-11-30 20:06
const rootEl = document.getElementById(\'root\');

ReactDOM.render(
    
        
            
              


        
相关标签:
10条回答
  • 2020-11-30 20:57

    Another solution is to use a state and lifecycle hooks in the routed component and a search statement in the to property of the <Link /> component. The search parameters can later be accessed via new URLSearchParams();

    <Link 
      key={id} 
      to={{
        pathname: this.props.match.url + '/' + foo,
        search: '?foo=' + foo
      }} />
    
    <Route path="/details/:foo" component={DetailsPage}/>
    
    export default class DetailsPage extends Component {
    
        state = {
            foo: ''
        }
    
        componentDidMount () {
            this.parseQueryParams();
        }
    
        componentDidUpdate() {
            this.parseQueryParams();
        }
    
        parseQueryParams () {
            const query = new URLSearchParams(this.props.location.search);
            for (let param of query.entries()) {
                if (this.state.foo!== param[1]) {
                    this.setState({foo: param[1]});
                }
            }
        }
    
          render() {
            return(
              <div>
                <h2>{this.state.foo}</h2>
              </div>
            )
          }
        }
    
    0 讨论(0)
  • 2020-11-30 20:59

    Use render method:

    <Route exact path="/details/:id" render={(props)=>{
        <DetailsPage id={props.match.params.id}/>
    }} />
    

    And you should be able to access the id using:

    this.props.id
    

    Inside the DetailsPage component

    0 讨论(0)
  • 2020-11-30 21:01

    If you want to pass props to a component inside a route, the simplest way is by utilizing the render, like this:

    <Route exact path="/details/:id" render={(props) => <DetailsPage globalStore={globalStore} {...props} /> } />
    

    You can access the props inside the DetailPage using:

    this.props.match
    this.props.globalStore
    

    The {...props} is needed to pass the original Route's props, otherwise you will only get this.props.globalStore inside the DetailPage.

    0 讨论(0)
  • 2020-11-30 21:02

    Use the component:

    <Route exact path="/details/:id" component={DetailsPage} />
    

    And you should be able to access the id using:

    this.props.match.params.id
    

    Inside the DetailsPage component

    0 讨论(0)
提交回复
热议问题