2017-09-07 2 views
1

리얼 라우터 v4를 사용하여 라우트를 렌더링하고 있습니다. 나는 아이템 목록과 기존의 편집/새로운 아이템 추가로가는 간단한 루트 컴포넌트를 가지고있다. 이것은 부트 스트랩으로 구축 된 간단한 탭 구성 요소입니다. 경로에 id 속성이 있는지 여부에 따라 탭 구성 요소의 제목을 Add new 또는 Edit existing으로 변경하고 싶습니다.라우트 구성 요소의 라우트 속성에 액세스하는 리액터 라우터

코드의 가독성을 높이기 위해 추가 구성 요소를 만들지 않아도되는 것이 이상적입니다. 최고의 그중 location.pathname 속성을 읽을 수하고 편집 여부를 결정하거나 새로운 추가하는 데 사용할 것 - -

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>; 
} 

다양한 해킹있다 충분할 것이다하지만 난 느낌 도움이되지 수 누락 된 항목이 있음

답변

0

편집 할 경로와 분리 할 경로를 분리 할 수 ​​있지만 같은 구성 요소를 사용할 수 있습니다.

<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> 

는 그런 다음 Item 구성 요소에 당신은 this.props.type를 확인할 수 있으며, 그에 따라 렌더링.

1

Item 구성 요소에는 id에서 match까지 경로 매개 변수의 URL 매개 변수가 표시됩니다.

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

strId을 기반으로 탭 라벨을 변경할 수 있습니다.

if(strId){ 
    //use edit lable 
}else{ 
    //add label 
} 
관련 문제