2016-11-21 2 views
1

사용자가 탐색 할 때마다 알림을 받고 싶은 특정 구성 요소가 있습니다. 라우터에 전달 된 기록에 액세스 할 수있는 방법이 있습니까?React 구성 요소에서 history.listen에 액세스하는 방법?

<Router history={history}> 
    {// ...} 
</Router> 

하위 구성 요소 :이 작동하는지

var Component = React.createClass({ 
    componentDidMount: function() { 
    // history.listen(this.onRouteChange); 
    }, 
    onRouteChange: function() {}, 
    render: function() {...}, 
}); 

답변

0

내가 눈치 챘 :

import { browserHistory } from 'react-router'; 

var Component = React.createClass({ 
    componentDidMount: function() { 
    browserHistory.listen(this.onRouteChange); 
    }, 
    ... 
}); 

을하지만 라우터에 전달 된 실제 역사를 사용할 것처럼 보인다 오히려 맹목적으로 browserHistory을 사용하는 것보다. 어떤 경우에는 hashHistory 대신에 전달합니다. 여전히 더 나은 해결책을 고맙게 여길 것입니다!

import React from 'react' 
import PropTypes from 'prop-types' 
import { withRouter } from 'react-router' 

현재 위치의 경로를 나타내는 간단한 구성 다음은 이와 같은 "반응 - 라우터에서

1

사용 withRouter. 역사 소품에 대해서도 똑같이 작동하며, 위치 대신 역사를 사용하십시오.

class ShowTheLocation extends React.Component { 
    static propTypes = { 
    match: PropTypes.object.isRequired, 
    location: PropTypes.object.isRequired, 
    history: PropTypes.object.isRequired 
    } 

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

    return (
     <div>You are now at {location.pathname}</div> 
    ) 
    } 
} 

"연결됨"(redux // 용어를 사용하려면) 라우터에 새 구성 요소를 만듭니다. 답에 대한 https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

+0

감사합니다 :에서

const ShowTheLocationWithRouter = withRouter(ShowTheLocation) 

. 나는 그 위치에 접근하려고 시도하지 않았고, 이것은 꽤 직설적이다. 역사가 바뀔 때마다 콜백을 호출하려고했습니다. –

관련 문제