【发布时间】:2020-08-04 01:58:07
【问题描述】:
我正在使用来自 reactjs 的模态引导程序,其中 onLoad 我正在调用函数 captchGen() 并且我试图将验证存储在 H2 标记中
我收到无限循环错误:× 错误:重新渲染过多。 React 限制渲染次数以防止无限循环。
const Modals = (props) => {
const [validation , setValidation] = useState("");
const [result , setResult] = useState(0);
const [inputValue , setInput] = useState("");
const captchGen = () => {
const data1 = Math.round(10 * Math.random());
const data2 = Math.round(10 * Math.random());
const str = ` Enter ${data1} + ${data2} `
const sum = data1+data2
setValidation(str);
setResult(sum)
}
const handleInput = (e) => {
setInput(e.target.value)
}
const captchValidation = () => {
const x = result;
const y = inputValue;
if ( x === y) {
alert("success")
}
else {
alert("fail")
}
}
return (
<Modal {...props} onLoad={captchGen()} size="sm" aria-labelledby="contained-modal-title-vcenter" centered>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">Captcha</Modal.Title>
</Modal.Header>
<Modal.Body>
<input type = "text" placeHolder = "Enter the number" onChange = { e => handleInput(e)}></input>
<button onClick = {captchValidation} >Validate</button>
</Modal.Body>
<Modal.Footer>
<Button onClick={props.onHide}>Close</Button>
<Button variant="primary">Save changes</Button>
</Modal.Footer>
</Modal>
);
};
export default Modals;
这里是模态代码
const HomePage = () => {
const [modalShow, setModalShow] = useState(false);
return (
<Button variant="dark"
onClick={() => setModalShow(true)}
>Subscribe</Button>
<Modals
show={modalShow}
onHide={() => setModalShow(false)}
/>
)
}
【问题讨论】:
-
onLoad = {captchGen()} // 将其更改为 onLoad = {captchGen}
-
我没有得到这个`在H2标签内输入${data1} + ${data2}`
标签: reactjs