setState不会立即更新状态 [英] setState doesn't update the state immediately
问题描述
我想问一下当我做onclick事件时为什么我的状态没有改变。我刚才搜索过我需要在构造函数中绑定onclick函数,但状态仍未更新。这是我的代码:
I would like to ask why my state is not changing when I do an onclick event. I've search a while ago that I need to bind the onclick function in constructor but still the state is not updating. Here's my code:
import React from 'react';
import Grid from 'react-bootstrap/lib/Grid';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import BoardAddModal from 'components/board/BoardAddModal.jsx';
import style from 'styles/boarditem.css';
class BoardAdd extends React.Component {
constructor(props){
super(props);
this.state = {
boardAddModalShow: false
}
this.openAddBoardModal = this.openAddBoardModal.bind(this);
}
openAddBoardModal(){
this.setState({ boardAddModalShow: true });
// After setting a new state it still return a false value
console.log(this.state.boardAddModalShow);
}
render() {
return (
<Col lg={3}>
<a href="javascript:;" className={style.boardItemAdd} onClick={this.openAddBoardModal}>
<div className={[style.boardItemContainer,style.boardItemGray].join(' ')}>
Create New Board
</div>
</a>
</Col>
)
}
}
export default BoardAdd
推荐答案
你的状态需要一些时间来改变,因为 console.log(this.state.boardAddModalShow)
在执行之前执行state mutates,您将前一个值作为输出。所以你需要在回调中写入控制台到setState函数
Your state needs some time to mutate, and since console.log(this.state.boardAddModalShow)
executes before the state mutates, you get the previous value as output. So you need to write the console in the callback to the setState function
openAddBoardModal(){
this.setState({ boardAddModalShow: true }, function () {
console.log(this.state.boardAddModalShow);
});
}
setState
是异步的。这意味着你不能在一行上调用setState并假设下一个状态已经改变。
setState
is asynchronous. It means you can’t call setState on one line and assume state has changed on the next.
根据 React docs
according to React docs
setState()
不会立即改变this.state
但会创建
挂起状态过渡。在调用此
方法后访问this.state
可能会返回现有值。对于调用setState的同步操作没有
保证,并且可以为了性能增益调用
批次。
setState()
does not immediately mutatethis.state
but creates a pending state transition. Accessingthis.state
after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
为什么他们会使setState异步
这是因为setState会改变状态并导致重新渲染。这个
可能是一个昂贵的操作,并使其同步可能会留下
浏览器无响应。
This is because setState alters the state and causes rerendering. This can be an expensive operation and making it synchronous might leave the browser unresponsive.
因此,setState调用是异步的,也是为了更好的
UI体验和性能而进行批处理。
Thus the setState calls are asynchronous as well as batched for better UI experience and performance.
这篇关于setState不会立即更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!