简体   繁体   中英

How to send props to children in React Router v4?

I have to use fetch in children component, but I don't know how to send props in Route. Is there any option for doing that or do I have to do it some other way?

This is route in my parent component:

<Route path={`/beers/:beerId`} component={Beer}/>

Then I'd like to use fetch in children component:

    fetchData = () => {
    let url = `https://api.punkapi.com/v2/beers/${this.props.id}`;
    fetch(url, {method: 'get'}).then(resp => resp.json()).then((data) =>
        this.setState({
            data: data
        })
    );
};

If you are looking to get the beerId from the URL.You can get it from this.props.match.params.beerId .

You can also pass it directly the traditional way using the render method

<Route path={`/beers/:beerId`} render={()=><Beer id={YOURID}/>}/>

If you're using the render method you can access the id using this.props.id . But since you already have the beer id in the URL its best if you get it using this.props.match.params.beerId .

When a Route matches, it will inject three props to the component it holds:

  • location : Information about the current location.
  • history : Access to the browser history and methods to navigate through.
  • match : All matched URL parameters.

So, in your Beer component you can access the URL param beerId using match.params.beerId , and your Ajax call:

const {beerId} = this.props.match.params;

fetchData = () => {
    let url = `https://api.punkapi.com/v2/beers/${beerId}`;
    fetch(url, {method: 'get'}).then(resp => resp.json()).then((data) =>
        this.setState({
            data: data
        })
    );    
}   

You need to use the render attribute of the route. An example would be:

<Route path={`/beers/:beerId`} render={(props) => <Beer {...props} beerList={beerList} />} />

where beerList is a hypothetical function or variable which is passed as a prop down to to <Beer /> component.

Further info: A Simple React Router v4 Tutorial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM