[英]How do I render same component depending on the page the user is currently on?
I have a component called a Card.我有一个名为 Card 的组件。 I render it twice on page 1 and page 2 and it displays somewhat different content depending on the page .
我在第 1 页和第 2 页上渲染了两次,它根据页面的不同显示了一些不同的内容。 Here is my initial approach.
这是我最初的方法。
const Card = () => {
const [cardState, setCardState] = useState("firstpage");
const firstPageProducts = productArray.slice(0, 4);
const secondPageProducts = productArray.slice(5, productArray.length);
const [shownImages, setshownImages] = useState([]);
useEffect(() => {
const shownImages = firstPageProducts.slice(0, 2);
setshownImages(shownImages);
}, []);
if (cardState === "firstpage") {
return (
<div>
some first page stuff
</div>
);
} else if (cardState === "secondpage") {
return (
<div>
some second page stuff
</div>
);
}
};
I want it to have a way for it to be stateless in a way that I can define from the page in which I'm rendering the card state. I also want it to persist in that if I go back to page 1 it loads correctly page 1 stuff.我希望它有一种方法可以使它成为无状态的,我可以从我正在渲染卡片 state 的页面中定义它。我还希望它坚持下去,如果我 go 回到第 1 页,它会正确加载第 1 页的东西。
right now if I pass down the card state as a prop to the app it sometimes throws an error claiming that the component has not been rendered at all or if it does it changes both the first-page component and the second-page component.现在,如果我将卡片 state 作为 prop 传递给应用程序,它有时会抛出一个错误,声称该组件根本没有被渲染,或者如果它渲染了,它会同时更改第一页组件和第二页组件。 I'm fairly new to react and I've heard of stateless components.
我对反应还很陌生,我听说过无状态组件。 I was thinking this has the potential to be one of them.
我在想这有可能成为其中之一。
How can I achieve this?我怎样才能做到这一点?
I think what you want is prop.我想你想要的是道具。 Prop is something passed to
child component
in your case Card
from parent component like a Deck
component or something. Prop 是从父组件(例如
Deck
组件或其他组件)传递给案例Card
中的child component
组件的东西。 Idk if that exist in your app.如果您的应用程序中存在,请确认。
eg例如
const Deck = () => {
return (
<div>
<Card cardContent='I am first' productList={[1, 2, 3]} />
<Card cardContent='I am second' productList={[4, 5, 6]} />
</div>
);
};
const Card = ({ cardContent, productList }) => {
return <div>
<h1>{cardContent}</h1>
{productList.map((product) => {
return <p>{product}</p>
})}
</div>;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.