Let me explain the problem that I've faced recently.
I have React.js + Flux powered application:
find
article by id in array. That works pretty fine. I trigger action which makes request to server and propagates store with data, when I go to details screen then I just get the necessary article from that array in store. 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
Component could look as follows:
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} />; } });
The interesting part comes next:
What I've came up with is to use callback in action inside component and it feels much more cleaner:
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} />; } });
What's your input?
Consider move the second call to get a detail article to the ArticleDetails component componentDidMount() life cycle method.
So if the article is not set, do not render the ArticleDetails component at all by return null / false.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.