[英]Child component, infinitely re-rendering
我無法理解為什么我的組件被無限重新渲染
父渲染:這部分非常大,所以我只包括使用子組件的部分
<Container
style={{ alignItems: "center", height: 350, width: 1000 }}
>
<RenderQuestion
questionVersion={this.state.questionVersion}
base1={this.state.base1}
base2={this.state.base2}
exp1={this.state.exp1}
exp2={this.state.exp2}
ansbase={this.state.ansbase}
ansexp={this.state.ansexp}
multiple={this.state.multiple}
// EDIT: it might be a bit confusing but multiple here
is just a randomly generated number
/>
...
</Container>
子組件 - RenderQuestion //這正常工作
const RenderQuestion = (props) => {
switch (props.questionVersion) {
...
case 11:
return(
<Row style={{ paddingTop: "50px", fontFamily: "courier", fontWeight: "bold", fontSize: 70, }}>
{/* Left Side */}
<Col style={{
textAlign:"right"
}}>
<Undeterminable
operator={props.multiple}
base1={props.base1}
base2={props.base2}
exp1={props.exp1}
exp2={props.exp2}
/>
</Col>
{/* Equal Sign */}
<Col xs="1">=</Col>
{/* Right Side */}
<Col xs="4" style={{
textAlign:"left"
}}>
<span>
{props.ansbase}<sup>{props.ansexp}</sup>
</span>
</Col>
</Row>
);
...
Child's Child Component - Undeterminable //這是無限重新渲染的部分
const Undeterminable = (props) => {
let operator = "";
let result = "";
// random 1-4
let random = Math.floor(Math.random()*4)+1;
switch(props.operator) {
case 1:
operator = "+"
break;
case 2:
operator = "-"
break;
case 3:
operator = "x"
break;
case 4:
operator = "÷"
break;
};
switch(random){
case 1:
result = <span>
?<sup>{props.exp1}</sup>
{" "} {operator} {" "}
{props.base2}<sup>{props.exp2}</sup>
</span>
break;
case 2:
result = <span>
{props.base1}<sup>?</sup>
{" "} {operator} {" "}
{props.base2}<sup>{props.exp2}</sup>
</span>
break;
case 3:
result = <span>
{props.base1}<sup>{props.exp1}</sup>
{" "} {operator} {" "}
?<sup>{props.exp2}</sup>
</span>
break;
case 4:
result = <span>
{props.base1}<sup>{props.exp1}</sup>
{" "} {operator} {" "}
{props.base2}<sup>?</sup>
</span>
break;
}
return result;
}
TL:DR 描述此代碼應該做什么是它呈現一個基本方程,其中指數 x^a (+/-/*/÷) y^b 其中任何數字 (x/a/y/b) 是隨機加載為“?” 而不是它的價值
然而,該組件正在無限地重新渲染,因此在顯示時,它會不斷隨機改變“?”哪個項目,導致方程無限閃爍和變化。 最奇怪的是,操作符在無限渲染期間永遠不會改變。
編輯:在我的RenderQuestion
案例 10 中,我使用了一個不同的子組件Multiple
,它是這樣的:
const Multiple = (props) => {
let result = [];
for(let i = 0; i < props.multiple -1; i++){
result.push(<>{props.base1}<sup>{props.exp1}</sup> + </>)
}
return <span>{result}</span>;
};
它也無限渲染(如果我在這里的任何地方添加 console.log 語句,它將無限記錄),但是由於這不會更改顯示的數據或干擾應用程序的其余部分,我沒有在 OP 中提到它,但它似乎更多的信息可能會導致更好的理解
每次渲染組件時,都會在Undeterminable
內重新計算random
。 請注意, operator
值存儲在props
,並且具有正確的行為。
有幾種方法可以解決您的問題:
random
放入props
以存儲該值。useState
鈎子之類的東西將random
的值存儲在狀態中。 對於useState
,請確保導入它,然后嘗試以下操作:
import React, { useState } from 'react';
const Undeterminable = (props) => {
// random 1-4
const [random] = useState(Math.floor(Math.random() * 4) + 1);
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.