【问题标题】:React router v4 onUpdate反应路由器 v4 onUpdate
【发布时间】:2017-10-21 20:35:15
【问题描述】:
我最近更新了响应路由器版本 4。在以前的版本中,我使用 onUpdate 回调来触发一个函数,以在路由更改时使页面滚动到顶部。
onUpdate 似乎已被弃用,我在文档中的任何地方都找不到它被替换的内容。
还有其他人遇到过这个问题吗?
const handlePageChange = () => {
window.scrollTo(0, 0);
};
ReactDOM.render(
<Provider store={store}>
<Router onUpdate={handlePageChange} history={browserHistory}>
<Redirect from="/" to="/music" />
{routes}
</Router>
</Provider>,
document.getElementById('root')
);
【问题讨论】:
标签:
javascript
reactjs
ecmascript-6
react-router
【解决方案1】:
“onUpdate”已折旧。您可以在“Routes”中使用“onEnter”属性。
<Router history={browserHistory}>
<Route path="/" component={App} >
<IndexRoute component={Home} />
<Route path="/contact-us" component={ContactUs} onEnter={handlePageChange}/>
</Route>
</Router>
还需要修改你的“handlePageChange”函数如下:
const handlePageChange = () => {
window.scrollTo(0, 0);
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
}
【解决方案2】:
@Alireza 的回答方向正确,但还不够完整。
为了能够使用React's Context API 访问路由器,组件都必须是路由器的子组件,并且它应该定义contextTypes 属性:
static contextTypes = {
router: PropTypes.object
};
这将确保路由器连接到该组件。
此外,您不能(或不再?)subscribe 到路由器。但是,您可以将侦听器附加到历史记录:
this.context.router.history.listen(handlePageChange)
您可能希望在组件的 componentDidMount 生命周期方法中执行此操作。
【解决方案3】:
另一种选择是在页面组件挂载时滚动页面:
class NotFoundView extends React.Component {
componentDidMount() {
window.scrollTo(0, 0);
}
render() {
var props = this.props;
return (
<div className="NotFound">
<HeaderContainer />
<h1>Coming Soon!</h1>
</div>
)
}
}
export default NotFoundView;
【解决方案4】:
有一个叫做context.router.subscribe的东西作为替代品......
你可以使用这样的东西:
import React from 'react';
class App extends React.Component {
//something like this in your code
componentDidMount() {
this.context.router.subscribe(() => {
console.log("change router");
})
}
render() {
return <button>hi</button>;
}
}
export default App;