【问题标题】:React - Call method after redirectReact - 重定向后调用方法
【发布时间】:2019-04-13 23:46:29
【问题描述】:

我有两个不同的链接。一个是主页,另一个是图库。我在主页 3 上带有方法 scrollIntoView onClick 的链接,这些链接将我带到不同的部分。我想实现将我从画廊组件重定向到主页的方法,完成后调用方法scrollIntoView

goToContact 方法:

goToContact = e => {
    if (window.location.pathname === "/fotobudka/") {
      this.fbContactElement.scrollIntoView({
        behavior: "smooth",
        block: "start"
      });
    }
    if (window.location.pathname !== "/fotobudka") {
      this.changeUrl();
      this.goto();
    }
  };

更改网址将我重定向到主页:

changeUrl() {
    return <Redirect to="/fotobudka/" />;
  }

完成后:

goto = () => {
    setTimeout(() => {
      let fbContactElement = document.getElementById("contact-form");
      fbContactElement.scrollIntoView({
        behavior: "smooth",
        block: "start"
      });
    }, 100);
  };

我的方法效果很好,但我知道 SetTimeout 不是好的解决方案。我已经尝试过异步/等待,但我认为我还不足以实现它。

如何在不使用 SetTimeout 函数的情况下对其进行重构?

【问题讨论】:

标签: javascript reactjs react-router


【解决方案1】:

你必须使用 setState 来设置一个属性来渲染你的 render() 方法。

class MyComponent extends React.Component {
  state = {
    redirect: false
  }

  goTo = () => {...}

  goToContact = e => {
    this.setState({ redirect: true },
    ()=>goto());
  }

  render () {
    const { redirect } = this.state;

    if (redirect) {
      return <Redirect to='/fotobudka'/>;
    }

    return (...)
  }
}

你也可以在官方文档中看到一个例子:https://reacttraining.com/react-router/web/example/auth-workflow

【解决方案2】:

我解决了我的问题,在一个论坛中,我检查了通过间隔我们可以检查页面上是否已经存在项目。在 React 中它看起来像这样:

goto = selector => {
if (window.location.pathname !== "/fotobudka/") {
  this.constructor.changeUrl();
}
let checkExist = setInterval(() => {
  let element = document.getElementById(selector);
  if (element) {
    element.scrollIntoView({
      behavior: "smooth",
      block: "start"
    });
    clearInterval(checkExist);
  }
}, 100);
};

static changeUrl() {
  return <Redirect to="/fotobudka/" />;
}

【讨论】:

    【解决方案3】:

    您可以使用componentDidMount() 生命周期钩子在组件加载时执行一些代码。但是你必须通过传递一些查询参数来避免无限的更新周期,比如doScroll=true。现在您可以简单地检查您的 componentDidMount() 钩子中的查询参数并执行您的滚动功能

    【讨论】:

    • 是的,我这样做了,我的元素是未定义的
    • 你指的是哪个元素?
    • fbContactElement
    • 你能从你的应用创建一个在线演示吗?以便我们可以帮助您调试它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多