나는 루트로 작동하는 몇 개의 버튼이 있습니다. 경로가 변경 될 때마다 활성 버튼이 변경되었는지 확인하려고합니다.반응 라우터 v4에서 경로 변경 내용을 듣는 방법?
반응 라우터 v4에서 경로 변경 내용을들을 수있는 방법이 있습니까?
나는 루트로 작동하는 몇 개의 버튼이 있습니다. 경로가 변경 될 때마다 활성 버튼이 변경되었는지 확인하려고합니다.반응 라우터 v4에서 경로 변경 내용을 듣는 방법?
반응 라우터 v4에서 경로 변경 내용을들을 수있는 방법이 있습니까?
나는 location
소품을 얻기 위해 withRouter
을 사용합니다. 구성 요소가 있기 때문에 새로운 경로의 업데이트되면 값이 변경되었을 경우, 나는 확인 :
@withRouter
class App extends React.Component {
static propTypes = {
location: React.PropTypes.object.isRequired
}
// ...
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
this.onRouteChanged();
}
}
onRouteChanged() {
console.log("ROUTE CHANGED");
}
// ...
render(){
return <Switch>
<Route path="/" exact component={HomePage} />
<Route path="/checkout" component={CheckoutPage} />
<Route path="/success" component={SuccessPage} />
// ...
<Route component={NotFound} />
</Switch>
}
}
이 통화에 popstate를 트리거하지 않습니다
history v4 lib를 사용해야합니다. there
history.listen((location, action) => {
console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
console.log(`The last navigation action was ${action}`)
})
history.pushState()와 history.replaceState() 도움이되기를 바랍니다 이벤트이므로이 내용만으로는 모든 경로 변경 사항을 다루지는 않습니다. – Ryan
에서
이예 당신은 역사의 객체에서 얻을해야합니다, 위의 확장합니다. BrowserRouter
을 사용하는 경우 withRouter
을 가져오고 HoC로 구성 요소를 랩핑하여 히스토리 개체 속성 및 기능에 대한 소품을 통해 액세스 할 수 있습니다.
import { withRouter } from 'react-router-dom';
const myComponent = ({ listen }) => {
listen((location, action) => {
// location is an object like window.location
console.log(action, location.pathname, location.state)
});
return <div>...</div>;
};
export default withRouter(myComponent);
주의해야 할 유일한 것은 withRoutes과 history
액세스 할 수있는 대부분의 다른 방법이 그것으로 그들은 드 구조로 객체를 소품을 오염 것처럼 보인다는 것이다.
대답은 질문에 관계없이 뭔가를 이해하는 데 도움이되었습니다. :) 그러나'withRoutes'를'withRouter'로 수정하십시오. –
네, 미안합니다. 지적 해 주셔서 고맙습니다. 나는 그 게시물을 수정했다. 질문의 맨 위에 올바른 가져 오기를 넣은 다음 코드 예제에서 잘못 입력했습니다. –
[withRouter의 현재 버전] (https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md)은 'history'대신에 'history'를 전달한다고 생각합니다. 변수'listen'. – mikebridge
반응 라우터 v4에서 'this.props.location.pathname'을 사용하십시오. – ptorsson