【问题标题】:How to add items to the watchlist in reactJs?如何在 reactJs 中将项目添加到关注列表?
【发布时间】:2022-01-13 11:24:28
【问题描述】:

我想弄清楚如何将项目添加到监视列表,

这里尝试执行的步骤是,当用户单击添加按钮时,应将项目添加到我创建的监视列表页面/组件中。

请查看组件的层次结构。 我想在关注列表页面上显示添加的项目。

请看我试过的代码。

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>

当我尝试检查时,结果是,它显示项目已添加但无法传递给监视列表组件?如何使用道具来传递这个值并显示它们?

非常感谢任何帮助。

谢谢一百万

【问题讨论】:

标签: javascript reactjs react-hooks frontend


【解决方案1】:

在您的示例中,Button 没有在 handleWatchlist 中传递任何参数。我不知道Button 组件的外观如何,但传递 arg 可能类似于以下示例:

const Button = ({ onClick }) => {

  const value = "some value";

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

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

【讨论】:

【解决方案2】:

感谢您的支持,但我通过使用两种方法找到了解决方案,它们是

这是道具钻探,即在我的 App.js 中执行 useState 操作,这是我拥有产品和监视列表组件的主页。

这是我建议其他人使用的最好方法是使用 contextAPI 和 useContext 挂钩。一种在应用程序的任何位置传递任何数据的简单方法。

请在下面的代码框上查看完整的代码和工作解决方案。

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

工作应用,我可以在其中将产品添加到关注列表。

working demo app

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-05
    • 2014-08-23
    • 2019-11-26
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多