简体   繁体   中英

How to load a page with the data from a component in react

I'm new to react and I'm trying to open a new page (think product page on an e-commerce website) with the data on a card component (product card) when it is clicked. The card components get their data from a separate js file using . map() . map() . Could you please give suggestions on how this could be achieved?

Well, If the other page you are saying is opened using the same react app you could use history from react-router, something like:

history.push(to: 'yourpath', state: { the data you need to give to the other page })

But keep in mind this won't be visible on the URL so the user won't be able to share the URL with that information, another way to get this working is using the search params.

Something like yourwebsite.com/?param=PARAM1 then you can read them with vanilla JS.

Another way would be adding a param to the route of that new page where you define all the routes something like

<Route path='/yourPath:id'/>

So when you click on the product you can send the user to that URL with the respective ID then you will have to store your products in a place where you can find them with the id, for example calling an API. I hope this helps.

您可以定义产品 id之类的内容,并通过产品 id 找到您的目标数据,使用 useState 并为产品卡组件设置 [setData,Data] 状态,并使用 onClickHandler 运行一个函数,该函数映射您的 js 文件并使用定义的产品 id 查找目标数据然后更新数据状态

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM