官网说明:
setState()
enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.
Think of setState()
as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
setState()
does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state
right after calling setState()
a potential pitfall. Instead, use componentDidUpdate
or a setState
callback (setState(updater, callback)
), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater
argument below.
RN中的setState并不是立即执行的,事实上可以看成是一个request,类似一个异步执行方法。这就会造成在程序执行过程state并不一定是最新的,解决的方法与处理异步程序类似,在异步方法执行完之后再执行后续的方法,如:
setClassId(newid){ this.setState({ activeClassId:newid, },()=>{ return this.fetchData();//下一步要执行的方法 }) };
如果使用下面这种方式,fetchData并不能获得最新的state
setClassId(newid){ this.setState({ activeClassId:newid }); this.fetchData();//下一步要执行的方法 };