如何在 React 组件中保留 props 或 state?
我有一个组件 compA,它以数组形式接收 props 并使用它来显示元素。我需要将 compA 作为 prop 的 ids 附加到数组 idsToDisplay 中,以替换之前的状态。
const compA = (ids) => {
cost [idsToDisplay, setIdsToDisplay] = useState([]);
useEffect(() => {
/* I need both id-123 and id-456 here */
/* so idsToDisplay should ['id-123','id-456'] once both component calls has been finished.*/
/* Tried setIdsToDisplay([...idsToDisplay, ids]); But it causes the max depth update
warning.*/
},[idsToDisplay,ids]
}
<compA ids={["id-123"]} />
<compA ids={["id-456"]} />
感谢任何帮助!
I have a component, compA that receives props as an array and uses it to display an element. I need the ids that come down to compA as a prop to be appended to the array idsToDisplay which out replacing the previous state.
const compA = (ids) => {
cost [idsToDisplay, setIdsToDisplay] = useState([]);
useEffect(() => {
/* I need both id-123 and id-456 here */
/* so idsToDisplay should ['id-123','id-456'] once both component calls has been finished.*/
/* Tried setIdsToDisplay([...idsToDisplay, ids]); But it causes the max depth update
warning.*/
},[idsToDisplay,ids]
}
<compA ids={["id-123"]} />
<compA ids={["id-456"]} />
Appreciate any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定您要完成的工作,但是我可能会删除/添加一些可以改善此片段的事情,并将您的问题一起解决。
将IDS-S包装到“ {}”中,或将其替换为Props,然后您可以以
props.ids
访问它。
不确定
IDSTODISPLAY的逻辑是什么
在依赖项列表中不需要您只能拥有一个组件,然后在其中添加多个ID-S
类似的东西:
Not sure what you are trying to accomplish, but there are a few thing I might remove/add that would improve this snippet, and solve your problem all together.
Either wrap the ids-s into '{}' or replace it to props, and after that you can access it as
props.ids
Not sure what is the logic that maybe
idsToDisplay
is not needed in the dependency listYou can have just one component, and add multiple id-s there
Something like this: