【问题标题】:How to access history stack in React router?如何访问 React 路由器中的历史堆栈?
【发布时间】:2021-05-18 04:38:41
【问题描述】:

我正在尝试访问 react-router 的历史堆栈。

这是我想做的:

我使用 react.js 和 react-router 创建了一个板。

如果用户单击板上的列表之一,它将转到详细信息页面。

假设用户点击列表中 id 为 3 的文章,react-router 进入 id 为 3 文章的详情页,url 形式如下。

localhost:3000/board/3

在详情页,有前往列表按钮,当用户点击它时,页面将再次移动到列表页,我将使用history.back() 在这里。

到目前为止,使用 react-router 很容易实现。

但是用户可以访问另一个页面,例如个人资料页面。

如果用户通过个人资料页面访问详细信息页面,转到列表按钮的行为应该有所不同。它将用户推送到用户列表页面。

综上所述,前往列表按钮的作用如下:

board -> detail -> click go to the list -> board
profile -> detail -> click go to the list -> user-list

为了根据用户所在的位置将用户推送到不同的页面,我需要查看用户来自哪里,因此我需要查看历史堆栈或者有其他方法可以检查用户来自哪个 url ?

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    使用react-router-dom,您将无法直接访问浏览器的历史对象(即历史堆栈),但您不一定需要,因为您可以使用路由状态来发送“元”数据以及路由关于用户从哪里导航的过渡。

    Link to: object

    例如路由:<Route path="/detail">....</Route> 您可以有多个指向页面的链接,每个链接都提供唯一的状态。

    示例链接:

    <Link
      to={{
        pathname: '/details',
        state: {
          from: 'board',
        }
      }}
    >
      to details from board
    </Link>
    

    <Link
      to={{
        pathname: '/details',
        state: {
          from: 'profile',
        }
      }}
    >
      to details from profile
    </Link>
    

    或用于命令式导航

    history.push({
      pathname: '/details',
      state: {
        from: 'profile',
      }
    });
    

    路由状态放置在location对象上,在Details组件中访问路由状态并相应地发出后续导航。

    const targets = {
      board: "/board",
      profile: "/userlist",
    };
    
    ...
    
    const { state: { from } } = useLocation();
    const target = targets[from] ?? "/board";
    
    ...
    
    <Link to={target}>
      click go to the list
    </Link>
    

    或用于命令式导航

    history.push(target)
    

    【讨论】:

      【解决方案2】:

      在我们的导航中,我们传递了历史记录(代码块 1)。在基于函数的组件中,我们将拥有完整的历史堆栈(代码块 2)。请参阅 URL 以获取更多详细信息。

      网址:https://reactrouter.com/web/api/history

      代码块 1

      <Navbar.Collapse id='basic-navbar-nav'>
          <Route render={({ history }) => <SearchBox history={history} />} />
          <Nav className='ml-auto'>
              <LinkContainer to='/cart'>
                  <Nav.Link>
                      <i className='fas fa-shopping-cart'></i> Cart
                  </Nav.Link>
              </LinkContainer>
          </Nav>
      </Navbar.Collapse>
      

      代码块 2

      const SearchBox = ({ history }) => {
          const [keyword, setKeyword] = useState('')
        
          const submitHandler = (e) => {
            e.preventDefault()
            if (keyword.trim()) {
              history.push(`/search/${keyword}`)
            } else {
              history.push('/')
            }
          }
      };
      

      【讨论】:

        猜你喜欢
        • 2018-11-07
        • 2020-09-10
        • 2018-05-18
        • 2017-06-11
        • 2011-02-15
        • 1970-01-01
        • 2017-08-03
        • 2020-06-14
        • 1970-01-01
        相关资源
        最近更新 更多