【问题标题】:Unable to redirect a component with react-router-dom无法使用 react-router-dom 重定向组件
【发布时间】:2021-10-09 13:08:46
【问题描述】:

当点击带有 className= "card" <div className="card" onClick={()=>CallComponent(_id)}> 的 div 时,我一直在尝试重定向到 ProductId 组件

函数CallComponent是:

CallComponent = (_id) => {
   console.log("Clicked");
   <Link to="/productnew">
   </Link>;
   <Route path="/productnew" component={ProductId}></Route>
};

当在控制台中看到卡“Clicked”但未路由组件时

【问题讨论】:

  • 所以基本上你必须在点击 div 时导航到 /productnew 正确吗?
  • @GiovanniEsposito 是的
  • 我认为这会有所帮助React routing onClick
  • @DanDemon 你在使用带或不带钩子的 React 吗?

标签: javascript reactjs


【解决方案1】:

要以编程方式导航到/productnew 路由,您可以将Redirect 与状态变量结合使用。比如:

import { Redirect } from "react-router-dom";

...

state = { redirect: null };

CallComponent = (_id) => {
   console.log("Clicked");
   this.setState({ redirect: "/productnew" });
};


render() {
  if (this.state.redirect) {
    return <Redirect to={this.state.redirect} />
  }
  return(
  // Your Code goes here
  )
}

This 是一篇有趣的文章,如果您想了解有关此主题的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-22
    • 2018-10-14
    • 2022-06-24
    • 2019-06-28
    • 2018-02-04
    • 2019-02-05
    • 2018-05-21
    • 2022-01-24
    相关资源
    最近更新 更多