javascript - React 本机 setState 钩子重新打开模式
问题描述
我对本机反应(博览会)中的模态有一个奇怪的问题。我的模态看起来像这样:
const useNewCommentModal = () => {
const [showModal, setShowModal] = useState(false);
const [comment, setComment] = useState('');
const toggle = () => {
setShowModal(!showModal);
};
const NewCommentModal = () => (
<Modal visible={showModal} animationType="slide">
<View style={[t.pX4]}>
<TextInput
style={[t.bgWhite, t.p2, t.rounded, t.textLg]}
placeholder={'Post jouw reactie...'}
onChangeText={text => setComment(text)}
value={comment}
/>
</View>
</Modal>
);
return [toggle, NewCommentModal];
};
export default useNewCommentModal;
当我键入时,模态不断重新打开。当我删除它时:
onChangeText={text => setComment(text)}
问题消失了,但显然状态不再更新。为什么模型不断重新打开?
- 编辑 -
const [toggleModal, NewCommentModal] = useNewCommentModal(
'user',
route.params.user.id
);
<NewCommentModal />
解决方案
每次你的 useNewCommentModal 钩子运行时,它都会创建一个名为 NewCommentModal 的新函数,然后你将其用作组件<NewCommentModal />
(这部分非常重要)。对于 React,每一个新NewCommentModal
的都与之前的不同(因为你每次和每次渲染都创建新函数),React 将在新旧之间运行相等比较,NewCommentModal
这将返回 false,因此 React 将卸载旧模式并安装一个新模式这是地方。发生这种情况是因为您将函数称为组件。因此,您不应该NewCommentModal
从您的钩子中返回组件,而是返回一个将呈现某些内容的函数 ( renderNewCommentModal
),并且不将其作为组件调用,而是作为函数 ( {renderNewCommentModal()}
) 调用。或者更好的是,只从钩子返回数据,并使用这些数据在你的主组件中渲染一些东西
有关此问题的更详细说明,请参阅我之前的回答https://stackoverflow.com/a/60048240/8390411
推荐阅读
- sql - “非唯一索引”的目的是什么
- apache-flink - 无法使用 flink 读取 kinesis 流,出现 SdkClientException:无法执行 HTTP 请求:当前令牌 (VALUE_STRING)
- .net - 如何将代理添加到雪花 .NET 连接器?
- npm - npm 没有安装我的包的最新版本
- apache-kafka - 如何将Kafka流提交间隔与kafka流中的翻滚窗口同步?
- javascript - 通过 Graph Api 向 Teams 发送聊天/频道消息
- spring-security - LDAP 是以明文形式还是以编码文本形式存储用户密码?
- java - 创建新字符串时使用类引用类型 Object 和类引用类型 String 有什么区别?
- java - 试图解决这个 Java 问题:finding palindromes (String)
- javascript - nodeJS get 方法中的 HTTPS 模块