【问题标题】:Get data from URL using Inertia使用 Inertia 从 URL 获取数据
【发布时间】:2021-04-08 00:00:51
【问题描述】:

我正在使用InertiaJs 库创建链接,如下所示:

<InertiaLink href={`/item/`+ itemId}>Go to the page</InertiaLink>

点击这个,链接会是这样的:/item/156654

问题:如何使用 Inertia 从上面的链接中获取 itemId(156654,54654654, ... )?

我知道在 React 中有一个函数let history = useHistory();,但是这种方法对我不起作用。有什么替代方案?

【问题讨论】:

  • 澄清一下:当您说“从链接获取 ItemId”时,您的意思是在这个范围内,还是在另一个页面上? stackoverflow.com/questions/58840998/…这似乎有你需要的答案
  • @AaronMorefield,我想获取另一个时代的 id,在用户点击<InertiaLink href={/item/+ itemId}>Go to the page</InertiaLink>时将被重定向的页面中
  • 如果是这种情况,您能否将一些代码发布在您希望接收代码的位置以便我们提供帮助?
  • @AaronMorefield,这个想法很简单。我有组件A 我有这个代码:<InertiaLink href={/item/+ itemId}>Go to the page</InertiaLink>,单击链接我将被重定向到组件B。所以,我想知道如何从组件 B 中的 URL 获取 Id。请告诉我你是否得到我。你知道解决办法吗?
  • 我的猜测是你必须做一些手动的 URL 解析,这看起来很简单:)

标签: reactjs inertiajs


【解决方案1】:

您可以使用window.location 对象来获取实际的 URL,然后应用简单的解析来获取项目 ID:

const { pathname } = window.location
const splitPathname = pathname.split("/")
const itemId = splitPathname[splitPathname.length - 1]

我们只是获取由“/”分隔的 URL 的所有部分并获取最后一个部分,这将是项目 ID。

【讨论】:

    【解决方案2】:

    <InertiaLink /> 不为打开的页面提供任何上下文,因此您需要手动解析 URL。在下面的示例中,您可以找到 parsePageId() 函数,它实际上解析了 an optimal way 中的位置路径。

    // solution from https://stackoverflow.com/questions/4758103/last-segment-of-url-in-jquery
    const parsePageId = (path) => path.substring(path.lastIndexOf('/') + 1)
    
    const Page = () => {
      const pageId = parsePageId(window.location.pathname)
      
      // will render "Page id: js", because snippet href is "https://stacksnippets.net/js"
      return (
        <p>Page id: <b>{pageId}</b></p>
      )
    }
    
    
    ReactDOM.render(<Page />, document.querySelector("#root"))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="root" />

    【讨论】:

      猜你喜欢
      • 2021-10-13
      • 2013-06-19
      • 2020-11-07
      • 2016-01-18
      • 2015-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多