如何在 React 组件中保留 props 或 state?

发布于 2025-01-19 12:25:08 字数 588 浏览 0 评论 0原文

我有一个组件 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

缺⑴份安定 2025-01-26 12:25:08

不确定您要完成的工作,但是我可能会删除/添加一些可以改善此片段的事情,并将您的问题一起解决。

  1. 将IDS-S包装到“ {}”中,或将其替换为Props,然后您可以以props.ids

    访问它。

  2. 不确定IDSTODISPLAY的逻辑是什么在依赖项列表中不需要


  3. 您只能拥有一个组件,然后在其中添加多个ID-S

类似的东西:

const compA = ({ids}) => {
    const [idsToDisplay, setIdsToDisplay] = useState([]);
    useEffect(() => {
    setIdsToDisplay(ids);
    }, [ids]);
}

<compA ids={["id-123", "id-456"]}/>

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.

  1. Either wrap the ids-s into '{}' or replace it to props, and after that you can access it as props.ids

  2. Not sure what is the logic that maybe idsToDisplay is not needed in the dependency list

  3. You can have just one component, and add multiple id-s there

Something like this:

const compA = ({ids}) => {
    const [idsToDisplay, setIdsToDisplay] = useState([]);
    useEffect(() => {
    setIdsToDisplay(ids);
    }, [ids]);
}

<compA ids={["id-123", "id-456"]}/>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文