我希望这个问题还没有在某个地方得到解答而且我还没有找到它... 所以我对 React.js 还是个新手,但无论如何我总是用它尝试新事物。
我已经完成了研究,但提议的解决方案似乎都不适合我。我将留下一些我搜索过的示例:
How to use Redirect in the new react-router-dom of Reactjs
React-router route won't trigger
所以我基本上有这段代码:
clicked(mousePosX, mousePosY) {
let d = property.dist(mousePosX, mousePosY, this.x, this.y);
if (d < this.w && d < this.h) {
console.log("square"); //working until here
return <Link to="/test/" />; //not redirecting
}
}
我把它放在一个类 中,它在 p5 库的帮助下创建了一个正方形,该库也在内部 一个 const 箭头函数。
我也尝试过将 Link 标签更改为 Redirect 标签,但没有成功。
如果您想查看整个文件(或项目),请点击此处链接:
我想要它做的是在用户点击屏幕上的任何方 block 后将用户重定向到其他地方。
如果有任何帮助,我将不胜感激。提前致谢。
最佳答案
<Link/>
在您单击它之前不会重定向到其他地方,要以编程方式重定向您需要使用 <Redirect/>
组件。
更新您的 clicked
函数,当用户点击方框时,将状态中的redirect变量设置为true。
并在渲染函数中检查是否 redirect
是真的,如果它是 true
然后使用 <Redirect/>
组件重定向到其他地方,否则返回您的其他 UI 组件。
这是基本状态设置的样子-
constructor(props){
super(props);
this.state = {
redirect: false,
//other state data
}
}
clicked(mousePosX, mousePosY) {
let d = property.dist(mousePosX, mousePosY, this.x, this.y);
if (d < this.w && d < this.h) {
console.log("square");
this.setState({
redirect:true, //set redirect to true
});
}
}
在你的渲染函数中
render(){
if(this.state.redirect){
return <Redirect to="/test" />
}
else{
//return something else
}
}
关于javascript - React router Link 不会在 if 语句后更新路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59098844/