react如何監聽路由url變化


"componentWillReceiveProps"
"shouldComponentUpdate"
"componentWillUpdate"
"render"
"componentDidUpdate"

使用這些生命周期鈎子可以監聽到路由相同,參數不同的變化,但是監聽不到完全不相同的url的變化。即使路由不同,componentDidMount組件內容所更新的東西變了,但是代碼變了,頁面沒有變,找到了一種方法。withRouter

參考:https://reacttraining.com/react-router/web/api/withRouter

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

// A simple component that shows the pathname of the current location
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>
    )
  }
}


export default withRouter(ShowTheLocation) //組件名稱,導出該組件,保證在最外邊

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM