reactjs - React hooks 通过子节点更新父状态并重新渲染

标签 reactjs react-hooks

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

在我的 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;

最佳答案

在将项目添加到数组时,您似乎没有正确使用 useState Hook 。您需要使用 ... 传播运算符。尝试将您的代码更改为如下内容:

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

此外,在使用某些事件(例如 mousemove)时,您需要使用回调版本:

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

关于reactjs - React hooks 通过子节点更新父状态并重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69545721/

相关文章:

reactjs - React.useState(<initialState>) 如何随着 <initialState> 更新而更新?

javascript - 如何限制我的 React 组件的大小并添加滚动?

javascript - 使用 console.log 时,我的 ReactJs 代码在控制台中打印两次值

javascript - 更新的状态在方法的返回语句中没有用

reactjs - 如何确保组件内的常量仅在 React (Native) 中使用钩子(Hook)启动时计算一次?

reactjs - 当父组件的状态更改时,子组件不会重新渲染

reactjs - 无法从 react 选择 AsyncSelect 下拉列表中获取所选值

reactjs - 将箭头函数传递给使用钩子(Hook)的组件会导致 useEffect 再次触发

reactjs - 如何使用 ReactCSSTransitionGroup 在 React 中对元素高度进行动画处理?

javascript - 如何从自定义 react 钩子(Hook)丰富数据