2017-01-28 11 views

答えて

17

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

はそれが

+1

反応ルータv4で 'this.props.location.pathname'を使用します。 – ptorsson

3

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}`) 
}) 
+0

history.pushStateを(ホープ)とhistory.replaceState()呼び出しがpopstateをトリガしません。これだけではすべてのルート変更がカバーされるわけではありません。 – Ryan

17

から

例には、履歴オブジェクトで取得する必要があります。 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アクセスするには、他のほとんどの方法はそれに彼らド・構造などのオブジェクトを小道具を汚染するように見えるということです。

+0

答えは質問に関係なく何かを理解するのを助けました:)。しかし 'withRoutes'を' withRouter'に修正してください。 –

+0

申し訳ありませんが、それを指摘していただきありがとうございます。私はその投稿を修正した。質問の先頭に正しいインポートを入れて、コード例で誤って入力しました。 –

+2

[現在のバージョンのwithRouter](https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md)は、変数 'listen'。 – mikebridge

関連する問題