簡體   English   中英

Flux + React.js - 動作中的回調是好還是壞?

[英]Flux + React.js - Callback in actions is good or bad?

讓我解釋一下我最近遇到的問題。

我有React.js + Flux驅動的應用程序:

  • 文章的列表視圖 (注意:應用程序中有多個不同的列表)和文章詳細信息視圖
  • 但是每個列表只有一個API端點返回文章數組。
  • 為了顯示我需要在數組中通過id find文章的細節。 這很好用。 我觸發了向服務器發出請求並使用數據傳播存儲的操作,當我轉到詳細信息屏幕時,我只是從存儲中的該數組中獲取必要的文章。
  • 當用戶在列表(商店為空)之前登陸文章詳細信息視圖時,我需要發出請求。
  • 流程看起來像: User loads details view - > component did mount - > stores are empty - > rendered empty - > fetchArticles action is triggered - > request response is 200 - > stores now have list of articles - > component did update - > rendered with data successfully
  • 組件可能如下所示:

     let DetailsComponent = React.createClass({ _getStateFromStores() { let { articleId } = this.getParams(); return { article: ArticleStore.getArticle(articleId) }; }, componentDidMount() { // fire only if user wasn't on the list before // stores are empty if (!this.state.article) { ArticleActions.fetchArticles('listType'); } }, render() { return <ArticleDetails article={this.state.article} />; } }); 

接下來是有趣的部分:

  • 現在我需要向服務器發出另一個請求,但請求選項取決於文章詳細信息 這就是我需要在詳細信息視圖中的第一個請求之后發出第二個請求的原因。
  • 我嘗試了幾種方法,但所有方法看起來都很難看。 我不喜歡從商店那里調用讓商店變得太復雜的行為。 在這種情況下調用操作內部的操作不能很好地工作,因為我需要在該操作中的商店中查找文章。

解決方案(?!)

  • 我想出的是在組件內部使用回調,感覺更清潔:

     let DetailsComponent = React.createClass({ _getStateFromStores() { let { articleId } = this.getParams(); return { article: ArticleStore.getArticle(articleId) }; }, componentDidMount() { if (!this.state.article) { ArticleActions.fetchArticles('listType', () => { this._requestAdditionalData(); }); } this._requestAdditionalData(); }, _requestAdditionalData() { if (this.state.article) { ArticleActions.fetchAdditional(this.state.article.property); } }, render() { return <ArticleDetails article={this.state.article} />; } }); 

你的意見是什么?

考慮移動第二個調用以獲取ArticleDetails組件componentDidMount()生命周期方法的詳細文章。

因此,如果未設置文章,請不要通過返回null / false來呈現ArticleDetails組件。

暫無
暫無

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

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