我想用以下代码显示一个弹出窗口:
const [showPopup, setShowPopup] = useState(false);
我通过这种方式处理显示/设置弹出:
<Popup open={showPopup} onClose={() => setShowPopup(false)} modal>
<span> Popup content </span>
</Popup>
{meta.error === 'codigo 2 fatores incorreto' ? (
setShowPopup(true)
) : (
<Popup style={{ visibility: "hidden" }}>.</Popup>
)}
当它在情况下(meta.error === 'codigo 2 fatores incorreto')下降时,他会在一个循环中下降,并出现以下错误:(重新渲染太多。React 限制了渲染的数量以防止无限循环。) ,有人知道怎么解决吗?
我使用了这个文档https://react-popup.elazizi.com/component-api/
整个组件[工作]:
import React, { useState, useEffect } from 'react';
import { ErrorMessage, useField } from "formik";
import { StyledTextInput, StyledLabel, StyledIcon, ErrorMsg } from "./Styles";
// Eye for password
import { FiEyeOff, FiEye } from "react-icons/fi";
//pop up style.css
import '../assets/css/popup.css'
// Import popup lib
import Popup from "reactjs-popup";
import 'reactjs-popup/dist/index.css';
function MyComponent() {
const [state, setState] = useState();
setState(true);
return (
<Popup model
trigger={open => <MyComponent open={open} />}
position="right center"
closeOnDocumentClick
>
<span> Popup content </span> </Popup>
);
}
export const TextInput = ({ icon, ...props }) => {
const [field, meta] = useField(props);
const [showpass, setShowpass] = useState(false);
const [showPopup, setShowPopup] = useState(false);
useEffect(() => {
if(meta.error === 'codigo 2 fatores incorreto'){
setShowPopup(true);
}
}, [meta.error])
return (
<div style={{ position: "relative" }}>
<StyledLabel htmlFor={props.name}>{props.label}</StyledLabel>
{props.type !== "password" && (
<StyledTextInput
invalid={meta.touched && meta.error}
{...field}
{...props}
/>
)}
{props.type === "password" && (
<StyledTextInput
invalid={meta.touched && meta.error}
{...field}
{...props}
type={showpass ? "text" : "password"}
/>
)}
<StyledIcon>{icon}</StyledIcon>
{props.type === "password" && (
<StyledIcon onClick={() => setShowpass(!showpass)} right>
{showpass && <FiEye />}
{!showpass && <FiEyeOff />}
</StyledIcon>
)}
{meta.touched && meta.error ? (
<ErrorMsg>{meta.error}</ErrorMsg>
) : (
<ErrorMsg style={{ visibility: "hidden" }}>.</ErrorMsg>
)}
<Popup open={showPopup} onClose={() => setShowPopup(false)} modal>
{close => (
<div className="modal">
<button className="close" onClick={close}>
×
</button>
</div>
)}
</Popup>
{meta.error === "codigo 2 fatores incorreto" ? (
!showPopup ? ( setShowPopup(true)) : ("") // <-- Only set state if not true
) : <Popup>.</Popup>}
</div>
);
};