如何在 Qwik City 的布局和页面中访问请求数据

huangapple go评论43阅读模式
英文:

How to access request data in layouts and pages in Qwik City

问题

我要翻译的内容:

I'm creating an application Qwik and Qwik City.

I want to show something in my layout, only if it's the home page.

This is my layout.jsx:

const Layout = component$((props) => {
    // console't see anything related to request
    const isHomePage = true; // how can I know I'm inside the home page?
    return <>
         {isHomePage && <TopBar />}
         
    </>
})
英文:

I'm creating an application Qwik and Qwik City.

I want to show something in my layout, only if it's the home page.

This is my layout.jsx:

const Layout = component$((props) =&gt; {
    // console.log(props); // I don&#39;t see anything related to request
    const isHomePage = true; // how can I know I&#39;m inside the home page?
    return &lt;&gt;
         {isHomePage &amp;&amp; &lt;TopBar /&gt;}
         
    &lt;/&gt;
})

答案1

得分: 3

import { component$, Slot } from "@builder.io/qwik";
import { loader$, useLocation } from "@builder.io/qwik-city";

export const useUser = loader$(async ({ fail }) => {
  try {
    const res = await fetch("https://api.github.com/users/harshmangalam");
    const user = await res.json();
    return {
      user,
    };
  } catch (error) {
    return fail(500, {
      error: "Something went wrong",
    });
  }
});

export default component$(() => {
  const user = useUser();
  const {
    url: { pathname },
  } = useLocation();
  const isHomePage = pathname === "/";
  return (
    <div>
      {isHomePage && <pre>{JSON.stringify(user.value, null, 4)}</pre>}
      <Slot />
    </div>
  );
});
英文:
import { component$, Slot } from &quot;@builder.io/qwik&quot;;
import { loader$, useLocation } from &quot;@builder.io/qwik-city&quot;;

export const useUser = loader$(async ({ fail }) =&gt; {
  try {
    const res = await fetch(&quot;https://api.github.com/users/harshmangalam&quot;);
    const user = await res.json();
    return {
      user,
    };
  } catch (error) {
    return fail(500, {
      error: &quot;Something went wrong&quot;,
    });
  }
});

export default component$(() =&gt; {
  const user = useUser();
  const {
    url: { pathname },
  } = useLocation();
  const isHomePage = pathname === &quot;/&quot;;
  return (
    &lt;div&gt;
      {isHomePage &amp;&amp; &lt;pre&gt;{JSON.stringify(user.value, null, 4)}&lt;/pre&gt;}
      &lt;Slot /&gt;
    &lt;/div&gt;
  );
});

huangapple
  • 本文由 发表于 2023年2月14日 18:54:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75446804.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定