【问题标题】:React hooks updating parent state through child and rerenderingReact 钩子通过子更新父状态并重新渲染
【发布时间】:2021-12-01 08:33:05
【问题描述】:

我有依赖于父状态的组件。当我将父 useState 钩子传递给子时,组件似乎没有呈现。

在我的ChildA 组件上,我调用了一个函数来执行 props.updateFiles()。 ChildB 即使在 prop 更改后也没有渲染任何内容。

const Parent = () => {
    const [files, setFiles] = useState([]);

    return (
      <div>
        <ChildA files={files} updateFiles={setFiles} />
        <ChildB files={files} updateFiles={setFiles} />
      </div>
    );
  };
export default Parent;
const ChildA = (props) => {
  const appendFile = () => {
    let old = props.files;
    old.push({ name: "asdf" });
    props.updateFiles(old);
  };

  return (
    <div >
        <button onClick={appendFile}>append file</button>
    </div>
  );
};
export default ChildA;

const ChildB = (props) => {

  const renderProps = (items) => {
    let out = items.map(({ name }, index) => <div>{name}</div>);
    return out;
  };

  return (
    <div>
      {renderProps(props.files)}
    </div>
  );
};
export default ChildB;

【问题讨论】:

  • 您需要出示 ChildA

标签: reactjs react-hooks


【解决方案1】:

在向数组中添加项目时,您似乎没有正确使用 useState 挂钩。您需要使用 ... 扩展运算符。尝试将您的代码更改为以下内容:

const appendFile = () => {
   let old = props.files;
   props.updateFiles([...old, "asdf"]);
};

另外,在使用鼠标移动等事件时,需要使用回调版本:

const appendFile = () => {
   props.updateFiles(oldArray => [...oldArray, "asdf"]);
};

【讨论】:

    猜你喜欢
    • 2019-01-08
    • 1970-01-01
    • 2019-08-30
    • 2021-01-27
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 2021-08-21
    相关资源
    最近更新 更多