小智 146
我withRouter
用来得到location
道具.当组件由于新路由而更新时,我检查值是否更改:
@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>
}
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你
Mug*_*gen 78
v5.1 引入了有用的钩子 useLocation
https://reacttraining.com/blog/react-router-v5-1/#uselocation
import { Switch, useLocation } from 'react-router-dom'
function usePageViews() {
let location = useLocation()
useEffect(
() => {
ga.send(['pageview', location.pathname])
},
[location]
)
}
function App() {
usePageViews()
return <Switch>{/* your routes here */}</Switch>
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*ter 56
要扩展上述内容,您需要获取历史对象.如果您正在使用BrowserRouter
,则可以使用高阶组件(HoC)导入withRouter
和包装组件,以便通过props访问历史对象的属性和函数.
import { withRouter } from 'react-router-dom';
const myComponent = ({ history }) => {
history.listen((location, action) => {
// location is an object like window.location
console.log(action, location.pathname, location.state)
});
return <div>...</div>;
};
export default withRouter(myComponent);
Run Code Online (Sandbox Code Playgroud)
唯一需要注意的是withRouter和大多数其他访问方式history
似乎污染了道具,因为它们将对象解构为它.
Ser*_*kiy 30
你应该使用history v4 lib.
那里的例子
history.listen((location, action) => {
console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
console.log(`The last navigation action was ${action}`)
})
Run Code Online (Sandbox Code Playgroud)
小智 19
import React, { useEffect } from 'react';
import { useLocation } from 'react-router';
function MyApp() {
const location = useLocation();
useEffect(() => {
console.log('route has been changed');
...your code
},[location.pathname]);
}
Run Code Online (Sandbox Code Playgroud)
带钩子
Ale*_*lex 10
withRouter
,history.listen
和useEffect
(React Hooks)配合得很好:
const Component = ({ history }) => {
useEffect(() => history.listen(() => {
// do something on route change
// for my example, close a drawer
}), [])
//...
}
export default withRouter(Component)
Run Code Online (Sandbox Code Playgroud)
每当更改路线时,都会触发监听器回调,并且的返回值history.listen
是与配合使用的关闭处理程序useEffect
。
import { useHistory } from 'react-router-dom';
const Scroll = () => {
const history = useHistory();
useEffect(() => {
window.scrollTo(0, 0);
}, [history.location.pathname]);
return null;
}
Run Code Online (Sandbox Code Playgroud)
带挂钩:
import { useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import { history as historyShape } from 'react-router-prop-types'
const DebugHistory = ({ history }) => {
useEffect(() => {
console.log('> Router', history.action, history.location])
}, [history.location.key])
return null
}
DebugHistory.propTypes = { history: historyShape }
export default withRouter(DebugHistory)
Run Code Online (Sandbox Code Playgroud)
导入并渲染为<DebugHistory>
组件
对于反应钩子,我正在使用useEffect
import React from 'react'
const history = useHistory()
const queryString = require('query-string')
const parsed = queryString.parse(location.search)
const [search, setSearch] = useState(parsed.search ? parsed.search : '')
useEffect(() => {
const parsedSearch = parsed.search ? parsed.search : ''
if (parsedSearch !== search) {
// do some action! The route Changed!
}
}, [location.search])
Run Code Online (Sandbox Code Playgroud)
在此示例中,当路线更改时我向上滚动:
import React from 'react'
import { useLocation } from 'react-router-dom'
const ScrollToTop = () => {
const location = useLocation()
React.useEffect(() => {
window.scrollTo(0, 0)
}, [location.key])
return null
}
export default ScrollToTop
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
85746 次 |
最近记录: |