2017-12-08 4 views
0

のは、私は、次のルートが設定されているとしましょう(単なる例、実際のルートは、この厄介ではありません):反応ルータの異なるパラメータで現在のページにリンクするにはどうすればいいですか?

<Router> 
    <Switch> 
    <Route path="/app/fun/:userid/profile" component={Profile} exact/> 
    <Route path="/photos/:userid" component={Photos} exact/> 
    <Route path="/:userid/contact" component={Contact} exact/> 
    </Switch> 
</Router> 

から任意上記ページの、どのように私は同じにリンクすることができますページが異なるが、userid

例:

/** 
* Shared component that's rendered by Profile, Photos and Contact 
*/ 
class SharedComponent extends React.Component { 
    render() { 
    const bobId = 423423432; 

    return (
     <div> 
     <Link to={/* what to put here? */}> 
      Redirect to the same page but with Bob's userid 
     </Link> 
     </div> 
    ); 
    } 
} 

export default withRouter(SharedComponent); 

注:パスと

+0

ですどのように同じページから同じページにリンクするが、別のデータを渡すのあなたの質問? – linasmnew

+0

これはすべてのページで使用されている共有コンポーネントで、現在のページ(別のデータを使用)にリダイレクトするそのコンポーネントのリンクをレンダリングしたい – Vic

+0

私の質問を更新しました – Vic

答えて

0

が実は、私はへの道を見つけましたこれを行う。それが最善の方法だが、それが動作するかどうかわからない:

/** 
* Shared component that's rendered by Profile, Photos and Contact 
*/ 
class SharedComponent extends React.Component { 
    render() { 
    const { location, match } = this.props; 
    const bobId = 423423432; 
    const bobUrl = location.pathname.replace(match.params.userid, bobId); 

    return (
     <div> 
     <Link to={bobUrl}> 
      Redirect to the same page but with Bob's userid 
     </Link> 
     </div> 
    ); 
    } 
} 

export default withRouter(SharedComponent); 

を基本的に、私は現在のURL(location.pathname)を取り、新しいIDを持つ現在のユーザーID(match.params.userid)を交換しています(bobId

0

ルータV4を反応させるパスuserIdを使用すると、以下のような共有コンポーネントに小道具、

class Profile extends React.Component { 
    render() { 
     const bobId = 423423432; // Pass bobId with path from parent to child 
     return (
      <SharedComponent path={"/stuff1/stuff2/`${bobId}`/profile"} /> 
     ); 
    } 
} 


class SharedComponent extends React.Component { 
    render() { 
    return (
     <div> 
     <Link to={this.props.path}> 
      Redirect to the same page but with Bob's userid 
     </Link> 
     </div> 
    ); 
    } 
} 

export default withRouter(SharedComponent); 
+0

hmm ..正しいものを生成する必要があります私はそれを使用するたびに 'SharedComponent'に渡します。これは迷惑です... – Vic

関連する問題