【问题标题】:React router Link won't update route after if statement反应路由器链接不会在 if 语句后更新路由
【发布时间】:2020-03-24 16:48:32
【问题描述】:

我希望这个问题还没有在某个地方得到回答,我还没有找到它...... 所以我还是 React.js 的新手,但无论如何我总是尝试新的东西。

我已经完成了我的研究,但建议的解决方案似乎都不适合我。我将留下一些我搜索的示例:

How to use Redirect in the new react-router-dom of Reactjs

Redirecting in React

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
 }
}

我将它放在一个 class 中,它在 p5 库的帮助下创建了一个正方形,该库也是 inside 一个 const 箭头函数。

我也尝试将链接标签更改为重定向标签,但没有成功。

如果您想查看整个文件(或项目),请点击以下链接:

Whole file (github)

我想要它做的是在用户点击屏幕上的任何方块后将用户重定向到其他地方。

如果有任何帮助,我将不胜感激。提前致谢。

【问题讨论】:

  • &lt;Link/&gt; 在你点击它之前不会重定向到其他地方,要以编程方式重定向你需要使用&lt;Redirect/&gt; 组件。

标签: javascript reactjs react-router p5.js


【解决方案1】:

&lt;Link/&gt; 在您点击它之前不会重定向到其他地方,要以编程方式重定向您需要使用&lt;Redirect/&gt; 组件。

更新您的clicked 函数,当用户单击方框时,将状态下的重定向变量设置为true。 并在渲染函数中检查redirect 是否为真,如果是true,则使用&lt;Redirect/&gt; 组件重定向到其他地方,否则返回您的其他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
    }
}

【讨论】:

    【解决方案2】:

    link 标签应与任何 html 标签一起使用,如下所示 https://reacttraining.com/react-router/web/guides/quick-start

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      • 2020-07-27
      • 2017-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      相关资源
      最近更新 更多