【问题标题】:Changing the route when opening a modal but not navigating to it打开模态但不导航到它时更改路线
【发布时间】:2023-02-17 19:53:15
【问题描述】:

Instagram example

如上图所示,在用户配置文件中,用户可以单击他的一个帖子,打开包含该特定帖子的模式,此后 url 会更改但不会导航到另一个页面。

我正在尝试在我的应用程序中做同样的事情,我尝试过做 history.push 之类的事情,但它不起作用,我认为这是反应路由器的原因。

【问题讨论】:

  • 你在使用 react-router-dom 库吗?

标签: reactjs react-router


【解决方案1】:

要实现您描述的行为,您可以使用 React Router 来管理 URL 更改并显示带有帖子内容的模态。

  1. 在您的 React Router 配置中定义一个路由,该路由对应于您要显示的模态内容。例如
    <Route path="/posts/:postId" component={PostModal} />
    
    1. 在您的组件中,包含指向新路由的链接,并将帖子 ID 作为参数。
    <Link to={`/posts/${postId}`}>View Post</Link>
    
    1. 在您的 PostModal 组件中,使用 useParams 挂钩从 URL 访问帖子 ID 参数。然后,从您的 API 或存储中获取发布数据,并显示它。
    import { useParams } from 'react-router-dom';
    
    function PostModal() {
      const { postId } = useParams();
      // Fetch post data and display it in modal
    }
    

    之后,使用 CSS 将模态显示为现有内容之上的叠加层,并使用 JavaScript 适当地显示和隐藏模态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2018-06-01
    • 2018-08-10
    • 2016-11-21
    • 2019-01-11
    • 1970-01-01
    相关资源
    最近更新 更多