我使用Reflux,通常我在进行ajax调用后触发,并且效果很好。出于测试目的,我不需要ajax调用,并且我注意到除非我给出最小5ms超时,否则触发器将不起作用。这是工作而不是工作的例子。
不工作的例子:
window.threadStore = Reflux.createStore
init: ->
@state = @getInitialState()
@fetchThreads()
getInitialState: ->
loaded: false
threads: []
fetchThreads: ->
# ajax call for not Testing, and just trigger for Testing
@state.threads = FakeData.threads(20)
@state.loaded = true
@trigger(@state) # This will NOT work!
window.threadStore = Reflux.createStore
init: ->
@state = @getInitialState()
@fetchThreads()
getInitialState: ->
loaded: false
threads: []
fetchThreads: ->
# ajax call for not Testing, and just trigger for Testing
@state.threads = FakeData.threads(20)
@state.loaded = true
@trigger(@state) # This will NOT work!
这将有效:
window.threadStore = Reflux.createStore
init: ->
@state = @getInitialState()
@fetchThreads()
getInitialState: ->
loaded: false
threads: []
fetchThreads: ->
# ajax call for not Testing, and just trigger for Testing
@state.threads = FakeData.threads(20)
@state.loaded = true
setTimeout( =>
@trigger(@state) # This WILL work!
, 500)
你能解释一下为什么它没有延迟就可以工作吗?这是一个我不明白的错误。
答案 0 :(得分:5)
这是因为组件从getInitialState
获取空数组,并且在调用trigger
之后发生。
init
,这意味着在安装组件之前立即调用fetchThreads
中的触发器。当稍后安装侦听组件时,它会从getInitialState
上的商店获取空数组。
我建议进行以下更改:
window.threadStore = Reflux.createStore
init: ->
@state =
loaded: false
threads: []
@fetchThreads()
getInitialState: ->
@state # TODO: State should be cloned for sake of concurrency
fetchThreads: ->
# NOTE: Assign a new state for the sake of concurrency
@state =
loaded: true
threads: FakeData.threads(20)
@trigger(@state) # This will SHOULD work now ;-)