繁体   English   中英

Function 仅被传递给 React 子组件一次

[英]Function only being passed to React child component once

我有一些我不明白的地方。 我正在创建一个 React 功能组件的层次结构,如下所示:

const ContainerComponent = () => {
  const [total, setTotal] = useState(initialValue);
  const updateFunction = () => { console.log('It got called'); }

  return (
    <EntryComponent updateFunction={updateFunction} />
  );
}

const EntryComponent = ({updateFunction}) => {
  const services = [{}, {}, {}];

  return (
    {services.map((service) => <ServiceComponent updateFunction={updateFunction} />}
  );
}

const ServiceComponent = ({updateFunction}) => {
  return (
    <input type='checkbox' onChange={updateFunction} ></input>
  );
}

所以想法是 function 一直传递到ServiceComponent并附加到每个组件的复选框。 在更改 function 应该触发,运行代码并更新ContainerComponent中的total 问题是这没有正确发生,并且 function 似乎只传递给第一个ServiceComponent实例。 如果我将console.log(updateFunction)放到ServiceComponent中,我会看到 function 为第一个组件记录,其余两个undefined 即使对于 JavaScript 来说,这也很奇怪。 任何人都可以阐明发生了什么吗? 据我了解 function 应该能够像任何其他变量一样被传递,并且每个ServiceComponent都应该在需要时使用它。 实际上,如果我将第二个属性传递给子组件,即 object 或像 integer 这样的原语,那么它在每个子组件上都可以通过。 为什么我的 function 没有出现这种情况,我该如何解决?

编辑:我看到了问题,问题是我没有我想的那么聪明。 在精简版中,我将所有内容都提供给同一个循环中的子组件,但在实际项目中,子组件是在多个位置创建的,我忽略了将 function 属性传递给它们。 就我而言,这真是令人难以置信的愚蠢。 我把这个问题留在这里,因为你们中的许多人已经发布了回复,对此我很感激。

编程很难,我想我需要一个更好的大脑。

我尝试将您的代码重构为此

const ContainerComponent = () => {
  const [total, setTotal] = useState(0);
  const updateFunction = (e) => {
    console.log("update total stuff happens here");
    console.log(e);
  };

  return <EntryComponent updateFunction={updateFunction} />;
};

const EntryComponent = ({ updateFunction }) => {
  const services = ["one", "two", "three"];

  return (
    <>
      {services.map((service) => (
        <ServiceComponent updateFunction={updateFunction} />
      ))}
    </>
  );
};

const ServiceComponent = ({ updateFunction }) => (
  <input type="checkbox" onChange={updateFunction}></input>
);

它工作得很好。 尝试在你的入口组件中使用一个反应片段。

在作者更改提供的代码后编辑

你在这里得到了完全有效的代码。 我怀疑这与您通过的 function 有关。 将在您提供更多详细信息时回来查看。

暂无
暂无

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

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