javascript - React Router 阻止路由属性更新
问题描述
每次组件进行路由更改时,我都会遇到 react-router 更新道具的问题。
在我的文档中,我有多个部分,所有部分都链接到导航菜单.. 例如:
- /关于#关于我们
- /关于#联系人
在 about 组件中,我实现了一个这样的 scrollSpy 函数:
scrollSpy() {
if (this.isTransitioning) return;
let hash = this.getCurrentSection();
if (this.state.activeSection != hash) {
this.setState({ activeSection: hash });
history.pushState(null, null, hash);
}
}
还有这样的滚动功能
scrollTo(hash) {
this.isTransitioning = true;
let section = $(hash);
let body = $("html, body");
let navBar = $("#mainNav");
let top = section.offset().top - navBar.height() - 10;
body.stop().animate({
scrollTop: top
}, 800, 'swing', () => {
this.isTransitioning = false;
this.scrollSpy();
})
}
当从导航栏中选择时,我还实现了此功能以将文章滚动到预期部分。
componentDidUpdate(prevProps, prevState) {
if (this.props.location.hash != prevProps.location.hash) {
this.scrollTo(this.props.location.hash);
}
}
现在,问题是,当我像这样插入一行以将历史记录更新到 scrollSpy 中时:
scrollSpy() {
if (this.isTransitioning) return;
let hash = this.getCurrentSection();
if (this.state.activeSection != hash) {
this.setState({ activeSection: hash });
history.pushState(null, null, hash);
this.props.history.push(hash);
}
}
系统将无限滚动,上下滚动。
似乎组件向 React-Router 发送信号,并且 react-router 更改道具,并且 scrollSpy 再次发送回 react-router。所以它有点卡在一个循环中。添加诸如isUpdating = true
没有帮助的变量,并使其行为不可预测。有时它会滚动,有时它不会滚动,有时它会跳回顶部。
如何确定 props 更改是来自我的 history.push 触发器还是用户单击导航栏?当用户单击导航栏时,我希望页面滚动到所需的部分顶部,即使它是屏幕上显示的当前部分。
谢谢
解决方案
推荐阅读
- python - TensorFlow - TFRecords 加载和转换带有边界框的图像
- amazon-web-services - AWS CLI 无法向 API Gateway 阶段变量添加权限
- javascript - 图像旁边的定位按钮
- blazor-webassembly - Blazor Webassembly 应用程序如何知道哪个用户已登录服务器端?
- kubernetes - 数据未跨容器共享
- python - 似乎不明白错误的原因
- regex - 为什么 sed 的正则表达式分组与普通正则表达式不同?
- amazon-web-services - 如何提高 AWS EC2 启动时间?
- reporting-services - 将一个超组的总和放入一个子组
- java - logging.properties 文件的存在会阻止写入日志