简体   繁体   中英

How to make redirect inside component in React router?

How to make redirect inside component in React router? I'm using react-rouer

import React from 'react'
import _ from 'lodash';
import FavoriteItem from '../components/FavoriteItem'

const FavoritesList = ({list}) => {

    let transitionToItem = ({id}) => {
        // make transition to `/details/${id}`
    };

    return (
        <ul className="list-group favorites-list">
            <FavoriteItem onFavoriteClick={ () => { transitionToItem(item); } } key={item.id} item={item}/>
        </ul>
    );
};


export default FavoritesList

Route:

<Route path="details/:item" name="details" component={DetailsPage}/>

I think the preferred way to do this would be to wrap whatever element you're clicking on in a react-router Link element and let the router handle everything.

<Link to=`/details/${item_id}`>Click me!</Link>

If you definitely want to take your approach, import the browserHistory module from react-router into your component and push the new URL right onto it.

import { browserHistory } from 'react-router';
...
let transitionToItem = ({id}) => {
  browserHistory.push(`/details/${id}`);
};

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