为了账号安全,请及时绑定邮箱和手机立即绑定

React 本机 setState 钩子重新打开模式

React 本机 setState 钩子重新打开模式

呼如林 2022-05-22 10:31:24
我对本机反应(博览会)中的模态有一个奇怪的问题。我的模态看起来像这样: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 />
查看完整描述

1 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

每次你的 useNewCommentModal 钩子运行时,它都会创建一个名为 NewCommentModal 的新函数,然后你将其用作组件<NewCommentModal />(这部分非常重要)。对于 React,每一个新NewCommentModal的都不同于以前的(因为你每次和每次渲染都创建新函数),React 会在新旧之间运行相等比较,NewCommentModal这将返回 false,因此 React 将卸载旧模式并安装一个新模式这是地方。发生这种情况是因为您将函数称为组件。因此,您不应该NewCommentModal从您的钩子中返回组件,而是返回一个将呈现某些内容的函数 ( renderNewCommentModal),并且不将其作为组件调用,而是作为函数 ( {renderNewCommentModal()}) 调用。或者更好的是,只从钩子返回数据,并使用这些数据在你的主组件中渲染一些东西



查看完整回答
反对 回复 2022-05-22
  • 1 回答
  • 0 关注
  • 159 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号