簡體   English   中英

反應setState和通量動作更新

[英]React setState and flux action update

我需要一個click函數來通過助焊劑動作對存儲進行更新,並更新組件的狀態。

示例:我有一個表單字段,其中包含故事的數據,以及一個狀態,用於說明表單的模式是否已打開。

// Initial state
return {
    story: this.props.story,
    modalIsOpen: true
}

-

// Click function to close the modal
closeModal: function(e){
    e.preventDefault();
    story.update(newStory)  // <== Flux action to update the story, which then updates this component 
    this.setState({modalIsOpen: false})  // <== To actually close the modal
}

但是,無論我把什么放在首位,似乎都沒有。 因此,如果我首先擁有story.update(newStory)它將執行一個,但不會執行this.setState({modalIsOpen: false}) ,反之亦然...

有什么想法我做錯了或如何執行的嗎?

this.setState()之后,您story.update()
可能是在您的動作調用之后,在執行this.setState()之前重新渲染了this.setState() 流程應為:

  • 您的組件調用story.update()
  • 商店監聽調度程序並進行更新
  • 商店發出變化
  • 您的組件傾聽變化
  • 組件內部響應存儲更新的方法setState( {modalIsOpen: false} )

另外,似乎您的story不需要處於狀態:您的組件可以簡單地呈現this.props.story

如果您使用ES2015類創建React組件(而不是React.createClass() ),則可能會忘記將事件處理程序方法綁定到組件的上下文。 有幾種方法可以輕松完成此操作,這是一個很好的教程: http : //www.ian-thomas.net/autobinding-react-and-es6-classes/

我更喜歡使用autobind-decorator 使用它,您應該將組件修復為:

import autobind from "autobind-decorator";

class Foo extends React.Component {

  /* ... */

  @autobind
  closeModal: function(e){
    e.preventDefault();
    story.update(newStory)  // <== Flux action to update the story, which then updates this component 
    this.setState({modalIsOpen: false})  // <== To actually close the modal
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM