如果没有init的延迟,Reflux触发器将无法工作

时间:2015-03-27 19:24:22

标签: reactjs reactjs-flux flux refluxjs

我使用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)

你能解释一下为什么它没有延迟就可以工作吗?这是一个我不明白的错误。

1 个答案:

答案 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 ;-)