如何解决为什么我的元素没有使用相同的反应状态实例?
我正在做一个随机报价应用程序,当我尝试更改正文背景和文本框文本颜色时,我似乎使用了错误的反应状态。车身背景颜色始终落后一步,我希望它们同时变为相同的颜色。 知道我的代码有什么问题吗?我只是在这里添加了开展业务的类组件。
P.S。我希望我的代码不太难读,我是一个初学者
class Quote extends React.Component {
constructor() {
super();
this.state = {
quote: [],author: [],apiData:[],color: ""
};
this.handleClick = this.handleClick.bind(this)
}
componentDidMount() {
//Here I made an API call for this.state.apiData to get my quotes
}
handleClick(){
var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16); //Here I get a random color
function getRandNum(min,max){
return Math.floor(Math.random()*(max-min)+min) //Here I get a random number in the range of my API array length
}
let randomNum = getRandNum(0,this.state.apiData.length)
this.setState({
quote: this.state.apiData[randomNum].text,author: this.state.apiData[randomNum].author
color: randomColor
})
document.body.style.backgroundColor = this.state.color;
console.log(this.state.color)
}
render() {
return (
<div class="quote-box">
<h1 style={{color: this.state.color}}> {this.state.quote}-"{this.state.author}" </h1>
<button
onClick={this.handleClick}
class="change-button"
style={{color: "white",backgroundColor: this.state.color}}
>Change
</button>
</div>
);
}
}
解决方法
因为setState异步设置状态(主体的背景色在状态中的颜色更新之前先更新)。您可以将第二个参数传递给setState
方法,状态更新后将调用该参数。
this.setState(
{
quote: this.state.apiData[randomNum].text,author: this.state.apiData[randomNum].author
color: randomColor
},() => document.body.style.backgroundColor = this.state.color
)
或者您也可以使用randomColor
变量设置主体的背景颜色。
this.setState({
quote: this.state.apiData[randomNum].text,author: this.state.apiData[randomNum].author
color: randomColor
})
document.body.style.backgroundColor = randomColor;
或者您可以使用componentDidUpdate
来检测状态的变化。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。