让我解释一下我最近遇到的问题。
我有React.js + Flux驱动的应用程序:
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} />;
}
});
您的意见是什么?
答案 0 :(得分:2)
考虑移动第二个调用以获取ArticleDetails组件componentDidMount()生命周期方法的详细文章。
因此,如果未设置文章,请不要通过返回null / false来呈现ArticleDetails组件。