2016-11-02 8 views
2

라우터 라우터를 사용하여 경로가 지정한 구성 요소가 아닌 다른 구성 요소의 경로 매개 변수에 액세스하고 싶습니다.Redux의 라우터 라우터 매개 변수

react-router, redux 및 react-router-redux가 다음과 같이 설정되어 있고 redux 저장소에서 reportId 매개 변수에 액세스하고 싶습니다.

const history = syncHistoryWithStore(browserHistory, store); 

const store = createStore(reducers); 

const routes = (
    <Router history={history}> 
     <Route path="/" component={MainLayout} > 
      <IndexRoute component={Home} /> 
      <Route path="reports"> 
       <Route path=":reportId" component={ReportViewerContainer} /> 
      </Route> 
     </Route> 
    </Router> 
); 

ReactDOM.render(
    <Provider store={store}>{router}</Provider>, 
    document.getElementById('root') 
); 

내가 반응 - REDUX - 라우터 경로 상태를 저장하기 위해 접선 시도했습니다,하지만 난의 내부에 저장된 유용한 것이없는 것으로 나타났습니다 REDUX 활성 행 노선의 전체 경로 외에. 이로 인해 redux에서 경로에서 reportId를 파싱하거나 내 자신의 사용자 지정 작업을 생성하고 내 ReportViewerContainer 구성 요소 내에서 componentWillReceiveProps 라이프 사이클 메서드로 업데이트하는 옵션이 남겨졌습니다. 더 좋은 방법이있을거야?

답변

1

그래서 context을 사용하여 라우터를 통과 할 위치를 가져올 수 있다고 생각합니다. (링크가 작동하는 방법에 대한 링크를 참조하십시오.) 이렇게하면 작업 할 수있는 확실한 방향이 제공됩니다.

이것은 국제화에서도 작동하도록 차선을 낮추는 데 도움이 될 수 있습니다.

class MyComponent extends React.Component { 
    static contextTypes = { 
     router: React.PropTypes.object 
    }; 

    render(){ 
     // By declaring context type here, and childContextTypes 
     // on the parent along with a function with how to get it, 
     // React will traverse up and look for the `router` context. 
     // It will then inject it into `this.context`, making it 
     // available here. 
    } 
} 
2

당신이 REDUX 저장소에 라우터에 액세스하려는 경우, withRouter (docs)라는 HOC있다. 올바르게 기억하면 라우터 상태가 소품으로 구성 요소로 전달됩니다.

import { withRouter } from 'react-router' 

export default withRouter(ReportViewerContainer);