首页 > 解决方案 > 当子组件更新时反应更新父级

问题描述

为什么父组件总是显示比子组件少 1?第一次更新后不会重新渲染。

export const Parent = (props) => {
  const [count, setCount] = React.useState(0);
  return (
    <View>
      <Text>Parent: {count}</Text>
      <Child updateCount={setCount} />
    </View>
  );
};

const Child = (props) => {
  const [count, setCount] = React.useState(0);

  const updateCount = () => {
    setCount((count) => count + 1);
    return props.updateCount(count);
  };
  return (
    <View>
      <Text>Child: {count}</Text>
      <Button title="add" onPress={updateCount} />
    </View>
  );
};

标签: javascriptreactjsreact-nativereact-hooksparent

解决方案


主要问题是您期望立即setCount发生,尽管它是一个异步操作。问题出在以下代码中的组件中:<Child />

const updateCount = () => {
    setCount((count) => count + 1)
    return props.updateCount(count)
}

从技术上讲,您期望count更新并传递给它,props.updatedCount同时它仍然具有以前的值。

这也与问题无关,但您实际上并不需要从更新状态的函数返回,因此只需删除return关键字。


有不同的选项可以解决这个问题。

  1. 仍然使用代码中的分离状态:

props.updateCount只需以与其他方式完全相同的方式调用setState

const updateCount = () => {
  setCount((count) => count + 1)
  props.updateCount((count) => count + 1)
}
  1. 保持一种状态<Parent />并通过道具传递:

所以主要的解决方案是:

export const Parent = (props) => {
  const [count, setCount] = React.useState(0);
  return (
    <View>
      <Text>Parent: {count}</Text>
      {/* passed here count as well: */}
      <Child updateCount={setCount} count={count} />
    </View>
  );
};

// destructure here updateCount and count
const Child = ({ updateCount, count }) => {
  return (
    <View>
      {/* using here count from parent */}
      <Text>Child: {count}</Text>
      {/* calling here updateCount from the props as: */}
      <Button title="add" onPress={() => updateCount((count) => count + 1} />
    </View>
  );
};
  1. 第三种选择是使用ContextAPI

通过使用Context,您可以执行以下操作,从文档中查看:

Context 提供了一种通过组件树传递数据的方法,而无需在每个级别手动传递 props。

通常我喜欢在Context我们拥有比当前更复杂的组件树时使用。所以我建议保留一个状态选项。


推荐阅读