【发布时间】:2020-10-08 03:02:21
【问题描述】:
我无法理解为什么我的组件会被无限重新渲染
父渲染:这部分非常大,所以我只包括使用子组件的部分
<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;
}
To 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 中提及它,但似乎更多信息可能会导致更好的理解
【问题讨论】:
-
如果有单独的问题,请附上其他组件的代码。
标签: javascript reactjs