javascript - 当子组件更新时反应更新父级
问题描述
为什么父组件总是显示比子组件少 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>
);
};
解决方案
主要问题是您期望立即setCount
发生,尽管它是一个异步操作。问题出在以下代码中的组件中:<Child />
const updateCount = () => {
setCount((count) => count + 1)
return props.updateCount(count)
}
从技术上讲,您期望count
更新并传递给它,props.updatedCount
同时它仍然具有以前的值。
这也与问题无关,但您实际上并不需要从更新状态的函数返回,因此只需删除return
关键字。
有不同的选项可以解决这个问题。
- 仍然使用代码中的分离状态:
props.updateCount
只需以与其他方式完全相同的方式调用setState
:
const updateCount = () => {
setCount((count) => count + 1)
props.updateCount((count) => count + 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>
);
};
- 第三种选择是使用
Context
API:
通过使用Context
,您可以执行以下操作,从文档中查看:
Context 提供了一种通过组件树传递数据的方法,而无需在每个级别手动传递 props。
通常我喜欢在Context
我们拥有比当前更复杂的组件树时使用。所以我建议保留一个状态选项。
推荐阅读
- python - Python - 从抽象类继承时属性返回旧值
- python - django.db.utils.IntegrityError:NOT NULL 约束失败:unesco_site.category_id
- javascript - 如何自动完成子目录中的文件(discord.js-commando)?
- react-native - React Native 中的 Google Photos API 集成
- java - 在 Spring Boot 中设计 REST API
- node.js - 具有节点 sdk 的 Hyperledger Fabric 服务器在未连接互联网时查询或调用速度很慢
- java - 即使在 Kafka 连接失败时继续 Spring Kafka 启动
- remote-debugging - 尝试在 ubuntu 18.04 上安装“gdb-multiarch”
- node.js - 使用 nuxt.js 在每个页面中验证 http 标头以进行身份验证
- python - 比较不同数组中的两个元素