2017-09-07 20 views
1

経路をレンダリングするためにリアクタ・ルータv4を使用しています。私はアイテムのリストにルーティングし、既存の編集/新しいアイテムを追加する単純なルートコンポーネントを持っています。これは、ブートストラップで構築されたシンプルなタブコンポーネントです。私は、ルートにidプロパティがあるかどうかによって、タブコンポーネントのタイトルをAdd newまたはEdit existingに変更したいと思います。経路コンポーネントの経路プロパティにアクセスする反応ルータ

理想的には、コードの可読性が向上するとは思わないので、追加のコンポーネントを作成する必要はありません。

public render() { 
    const { match, location } = this.props; 

    const customers = cx({ active: !location.pathname.includes("AddEdit") }); 
    const editItem = cx({ active: location.pathname.includes("AddEdit") }); 

    const hasIdParam = {/* Some way to read match params to get the id */}; 

    return <div className='nav-component-container'> 
     <nav> 
      <ul> 
       <li role="presentation" className={items}><NavLink to={`${match.url}/All`} activeClassName='active'>Items</NavLink></li> 
       <li role="presentation" className={editItem}> 
        <NavLink to={`${match.url}/AddEdit`} activeClassName='active'> 
         {/* I'd like this to say either new item or edit existing based on whether the current route has an id parameter or not */} 
        </NavLink> 
       </li> 
      </ul> 
     </nav> 
     <Switch> 
      <Route path={`${match.url}/All`} component={Customers} {...this.props}></Route> 
      <Route path={`${match.url}/AddEdit/:id?`} component={Item}></Route> 
     </Switch> 
    </div>; 
} 

様々なハックがある - location.pathnameプロパティを読んでいるようだと、それは編集だかどうかを確認したり、新しいを追加するためにそれを使用する最善のうち - 十分ですが、私は、私はだと感じて助けることができません何かが欠けている

答えて

0

編集と追加のルートを分けることができますが、同じコンポーネントをタイプpropで使用できます。あなたがthis.props.typeをチェックし、それに応じてレンダリングすることができ、あなたのItemコンポーネントに続いて

<Switch> 
     <Route path={`${match.url}/All`} component={Customers} {...this.props}></Route> 
     <Route path={`${match.url}/Details/:id?`} component={()=>(<Item type="detail" />)}></Route> 
     <Route path={`${match.url}/Edit/:id?`} component={()=>(<Item type="edit" />)}></Route> 
     <Route path={`${match.url}/Add/:id?`} component={()=>(<Item type="add" />)}></Route> 
    </Switch> 

1

Itemコンポーネントには、URLパスのidmatchのルートパスのオブジェクトが表示されます。

var strId = props.match.params.id //ecma5 
let strId = this.props.match.params.id //ecma6 

strIdに基づいて、タブラベルを変更することができます。

if(strId){ 
    //use edit lable 
}else{ 
    //add label 
} 
関連する問題