Skip to content

Commit 885b822

Browse files
committed
fix: setState callback should emit in willMount
see detail in the test case
1 parent c287beb commit 885b822

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

packages/nerv/__tests__/lifecycle.spec.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,36 @@ describe('Lifecycle methods', () => {
238238
expect(spy.calledOnce).toBe(true)
239239
})
240240

241+
it('setState in setState callback should work in componentWillMount', () => {
242+
const spy = sinon.spy()
243+
class App extends Component {
244+
constructor (props) {
245+
super(props)
246+
this.state = {
247+
msg: ''
248+
}
249+
}
250+
251+
componentWillMount () {
252+
this.setState({
253+
msg: 'test'
254+
}, () => {
255+
this.setState({
256+
msg: 'test2'
257+
}, () => {
258+
spy()
259+
})
260+
})
261+
}
262+
render () {
263+
return <div>{this.state.msg}</div>
264+
}
265+
}
266+
267+
render(<App />, scratch)
268+
expect(spy.calledOnce).toBe(true)
269+
})
270+
241271
it('get latest state', () => {
242272
class App extends Component {
243273
constructor (props) {

packages/nerv/src/component.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,10 +86,11 @@ class Component<P, S> implements ComponentInst<P, S> {
8686

8787
clearCallBacks () {
8888
// cached the length of callbacks, or callbacks may increase by calling them in the same loop
89-
const len = this._pendingCallbacks.length
90-
for (let i = 0; i < len; i++) {
89+
let len = this._pendingCallbacks.length
90+
while (this._dirty ? this._pendingCallbacks.length : len) {
9191
const cb = this._pendingCallbacks.shift()!
9292
cb.call(this)
93+
len--
9394
}
9495
}
9596

0 commit comments

Comments
 (0)