首页 > 解决方案 > 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 触发器还是用户单击导航栏?当用户单击导航栏时,我希望页面滚动到所需的部分顶部,即使它是屏幕上显示的当前部分。

谢谢

标签: javascriptreactjsreact-router-v4

解决方案


推荐阅读