【发布时间】:2020-05-29 03:56:23
【问题描述】:
预期的组件行为: - 加载由“if”条件定义的动画 - 然后1000ms后,setTimeout函数会改变状态,从而渲染条件的'else'部分
其他详情 组件加载正常,但是,当我创建组件的另一个实例时,两个警报同时触发,并且 this.render.state 设置为 true。这可以防止动画作为条件语句的一部分加载,因为 state.render 为真......即使它应该为假......该组件的每个实例不应该显示默认的条件行为吗?
Name.js 组件
export class Name extends Component {
state = {
render: false,
};
componentDidMount() {
//alert('Test')
setTimeout(
function () {
//Start the timer
this.setState({ render: true }); //After 1 second, set render to true
}.bind(this),
1000
);
}
render() {
if (this.state.render === false) {
return (
<div className={styles.LContainer}>
<div className={styles.ldsRing}>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
);
} else {
console.log(this.state.render)
return (
<div className={styles.Container}>
<img
className={styles.imageO}
src={require("./Apple_logo_white.svg")}
/>
<div className={styles.textArea}>
<h1 className={styles.title}>{this.props.title}</h1>
<h2 className={styles.subtitle}>
{this.props.sub}
</h2>
<Input name="name" handleChange = {this.props.handleChange} />
<ScreenButton goDirection={this.props.backScreen} direction="back"/>
<ScreenButton goDirection={this.props.nextScreen} direction="next"/>
</div>
</div>
);
}
}
}
我也在使用 switch 语句来渲染这些组件,这和它有什么关系吗?
render() {
//Pulling information down from state:
const { step, name, interest, location } = this.state;
const values = { step, name, interest, location };
switch (step) {
case 1:
return (
<Welcome
nextScreen={this.nextScreen}
handleChange={this.handleChange}
values={values}
/>
);
case 2:
console.log(this.state.step);
//return <h1>GOLS</h1>
return (
<React.Fragment>
<Name
nextScreen={this.nextScreen}
backScreen={this.backScreen}
handleChange={this.handleChange}
values={values}
sub="Example text"
title="Example text"
/>
</React.Fragment>
);
case 3:
console.log(this.state.step);
return (
<React.Fragment>
<Name
nextScreen={this.nextScreen}
backScreen={this.backScreen}
handleChange={this.handleChange}
values={values}
sub="Example text"
title="Example text"
/>
</React.Fragment>
);
}
}
[1]: https://i.stack.imgur.com/U0v38.gif
【问题讨论】:
-
你在没有
bind this的情况下检查了这个 ` setTimeout( ()=> { //启动定时器 this.setState({ render: true }); //1秒后,设置render为true }, 1000 );` -
是的,由于某种原因,它在没有绑定的情况下无法编译。我不知道为什么有必要。
-
你确定,
state = { render: false, };这在不将其放入构造函数的情况下工作吗? -
我厌倦了你的建议,结果是一样的。问题是它会第一次为第一个组件加载动画,但对于第二个组件它什么也不做。在视频中,您可以看到加载圈有效,但是当我点击下一个组件时,下一个组件应该执行相同的加载动画,但它没有。
-
查看答案,它正在工作。因此,尝试将计时器增加到 5 秒,然后您将能够看到效果。由于 1 秒在页面加载时很快过去
标签: javascript reactjs