gpt4 book ai didi

javascript - React - 重定向后的调用方法

转载 作者:行者123 更新时间:2023-11-29 20:48:26 25 4
gpt4 key购买 nike

我有两个不同的链接。一个是主页,另一个是图库。我在主页 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();
}
};

更改 Url 将我重定向到主页:

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

完成后:

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

我的方法非常有效,但我知道 SetTimeout 不是好的解决方案。我已经尝试过 async/await 但我认为我还不够好来实现它。

如何在不使用 SetTimeout 函数的情况下重构它?

最佳答案

您必须使用 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

关于javascript - React - 重定向后的调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53242114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com