简体   繁体   English

如何将项目添加到 reactJs 中的监视列表?

[英]How to add items to the watchlist in reactJs?

I Am trying to figure out how can I add the items to watchlist,我想弄清楚如何将项目添加到监视列表,

The steps am trying to carry out here are, when a user clicks on add button, the items should be added to the watchlist page/component which I have created.我在这里尝试执行的步骤是,当用户单击添加按钮时,应将项目添加到我创建的监视列表页面/组件中。

Please see the hierarchy of the component.请查看组件的层次结构。 I would like to show added items on the watchlist page.我想在监视列表页面上显示添加的项目。

在此处输入图像描述

Please see the code I tried.请查看我尝试过的代码。

const [watchlist, setWatchlist] = useState ([]);

const handleWatchlist = (movieData) => {
   const newList = [...watchlist, movieData]
   setWatchlist(newList)
   console.log(newList)
}




<Button className = {classes.cardButton}size = "small" onClick = {  ()=> handleWatchlist(movie) }> Add </Button>

When I try to inspect, the result is, it shows the items are added but can not pass on to the watchlist component?当我尝试检查时,结果是,它显示项目已添加但无法传递给监视列表组件? How can use a prop to pass this value and show them?如何使用道具来传递这个值并显示它们?

![在此处输入图像描述

Any help is really appreciated.非常感谢任何帮助。

Thanks a million太感谢了

The Button doesn't pass any argument in handleWatchlist in your example.在您的示例中, Button未在handleWatchlist中传递任何参数。 I don't know how Button component looks like, but passing the arg could look like the example below:我不知道Button组件的外观,但传递 arg 可能类似于以下示例:

const Button = ({ onClick }) => {

  const value = "some value";

  return <button onClick={() => onClick(value)}>Button</button>;
};

const WatchList = () => {
...
return <Button onClick={handleWatchlist}>Add</Button>

Thanks for the support, but I figured out the solution by using two approaches and they are感谢您的支持,但我通过使用两种方法找到了解决方案,它们是

Which is props drilling, ie is to perform the useState action in my App.js which is my main page where I have product and watchlist component.这是道具钻探,即在我的 App.js 中执行 useState 操作,这是我有产品和监视列表组件的主页。

This is the best way I would suggest other people use as well is by using the contextAPI and useContext hooks .这是我建议其他人使用的最好方法是使用contextAPI 和 useContext hooks A simple and easy way to pass any data anywhere in the app.在应用程序的任何位置传递任何数据的简单方法。

Please see the full code with the working solution below on the codesandbox.请在代码框上查看完整代码以及下面的工作解决方案。

https://codesandbox.io/s/determined-nightingale-m2mtn?file=/src/components/Products https://codesandbox.io/s/determined-nightingale-m2mtn?file=/src/components/Products

The working app, where I can add the products to the watchlist.工作应用程序,我可以在其中将产品添加到监视列表。

working demo app工作演示应用程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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