英文:
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) => {
// console.log(props); // I don't see anything related to request
const isHomePage = true; // how can I know I'm inside the home page?
return <>
{isHomePage && <TopBar />}
</>
})
答案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 "@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>
);
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论