Javascript 为什么调用setState方法不';你不能马上改变状态吗?
好的,我会尽量快一点,因为这应该是一个简单的解决办法 我读过很多类似的问题,答案似乎很明显。一开始我什么都不用查!但是我有一个错误,我无法理解如何修复或为什么它会发生 详情如下:Javascript 为什么调用setState方法不';你不能马上改变状态吗?,javascript,html,reactjs,event-handling,Javascript,Html,Reactjs,Event Handling,好的,我会尽量快一点,因为这应该是一个简单的解决办法 我读过很多类似的问题,答案似乎很明显。一开始我什么都不用查!但是我有一个错误,我无法理解如何修复或为什么它会发生 详情如下: class NightlifeTypes extends Component { constructor(props) { super(props); this.state = { barClubLounge: false, seeTheTown: true,
class NightlifeTypes extends Component {
constructor(props) {
super(props);
this.state = {
barClubLounge: false,
seeTheTown: true,
eventsEntertainment: true,
familyFriendlyOnly: false
}
this.handleOnChange = this.handleOnChange.bind(this);
}
handleOnChange = (event) => {
if(event.target.className == "barClubLounge") {
this.setState({barClubLounge: event.target.checked});
console.log(event.target.checked)
console.log(this.state.barClubLounge)
}
}
render() {
return (
<input className="barClubLounge" type='checkbox' onChange={this.handleOnChange} checked={this.state.barClubLounge}/>
)
}
所以我有这两个console.log()
,它们应该是相同的。我正在将状态设置为与上面一行中的事件.target.checked相同
但它总是返回与它应该返回的相反的结果
我使用时也是如此!this.state.barClubLounge
;如果开始为false,则在我第一次单击时,它将保持为false,即使复选框是否选中取决于状态
这是一个疯狂的悖论,我不知道发生了什么,请帮忙 原因是设置状态是异步的,如果要使用回调
方法检查值,则不能期望更新的状态
值正好在设置状态
之后。将方法作为回调传递,该回调将在setState
完成其任务后执行
为什么setState是异步的
这是因为setState
会更改状态
,并导致重新渲染。这可能是一个昂贵的操作,使其同步可能会使浏览器无响应。
因此,setState
调用是异步的
,并且是批处理的,以获得更好的UI体验和性能
来自:
setState()不会立即改变this.state,但会创建
等待状态转换。调用此命令后访问this.state
方法可能返回现有值。没有
保证对setState的调用和可能发生的调用的同步操作
为提高性能而进行批处理
使用带有setState的回调方法:
要在设置状态
之后检查更新的状态
值,请使用如下回调方法:
setState({ key: value }, () => {
console.log('updated state value', this.state.key)
})
选中此项:
类夜生活类型扩展React.Component{
建造师(道具){
超级(道具);
此.state={
barClubLounge:错,
西斯敦:没错,
事件陈述:是的,
家庭友好:错
}
}
handleOnChange=(事件)=>{//Arrow函数绑定`this`
让值=event.target.checked;
if(event.target.className==“barClubLounge”){
this.setState({barClubLounge:value},()=>{//here
console.log(值);
console.log(this.state.barClubLounge);
//两者都将打印相同的值
});
}
}
render(){
返回(
)
}
}
ReactDOM.render(,document.getElementById('app'))
这是出于性能考虑而设计的。React中的setState是一个保证重新呈现组件的函数,这是一个昂贵的CPU进程。因此,它的设计者希望通过将多个渲染动作集中到一个渲染动作中来进行优化,因此setState是异步的 因为setState是一个异步函数。这意味着调用setState后,状态变量不会立即更改。因此,如果要在更改状态后立即执行其他操作,则应在setstate update函数中使用setstate的回调方法
handleOnChange = (event) => {
let inputState = event.target.checked;
if(event.target.className == "barClubLounge") {
this.setState({ barClubLounge: inputState}, () => { //here
console.log(this.state.barClubLounge);
//here you can call other functions which use this state
variable //
});
}
}
handleOnChange = (event) => {
let inputState = event.target.checked;
if(event.target.className == "barClubLounge") {
this.setState({ barClubLounge: inputState}, () => { //here
console.log(this.state.barClubLounge);
//here you can call other functions which use this state
variable //
});
}
}