6

我使用 Reflux,通常我在进行 ajax 调用后触发,并且效果很好。出于测试目的,我不需要 ajax 调用,并且我注意到除非我给出 5 毫秒的超时时间,否则触发器将不起作用。这是工作和不工作的例子。

不工作的例子:

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)

你能解释一下为什么它不能立即工作吗?应该这样做吗?这是一个错误还是我不明白的东西。

4

1 回答 1

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 ;-)
于 2015-04-01T06:41:24.893 回答