【发布时间】:2016-02-29 00:35:02
【问题描述】:
我正面临一个无限循环问题,我看不到是什么触发了它。它似乎在渲染组件时发生。
我有三个组件,组织如下:
TimelineComponent
|--PostComponent
|--UserPopover
TimelineComponenet:
React.createClass({
mixins: [
Reflux.listenTo(TimelineStore, 'onChange'),
],
getInitialState: function() {
return {
posts: [],
}
},
componentWillMount: function(){
Actions.getPostsTimeline();
},
render: function(){
return (
<div className="timeline">
{this.renderPosts()}
</div>
);
},
renderPosts: function (){
return this.state.posts.map(function(post){
return (
<PostComponenet key={post.id} post={post} />
);
});
},
onChange: function(event, posts) {
this.setState({posts: posts});
}
});
后组件:
React.createClass({
...
render: function() {
return (
...
<UserPopover userId= {this.props.post.user_id}/>
...
);
}
});
用户弹出框:
module.exports = React.createClass({
mixins: [
Reflux.listenTo(UsersStore, 'onChange'),
],
getInitialState: function() {
return {
user: null
};
},
componentWillMount: function(){
Actions.getUser(this.props.userId);
},
render: function() {
return (this.state.user? this.renderContent() : null);
},
renderContent: function(){
console.log(i++);
return (
<div>
<img src={this.state.user.thumbnail} />
<span>{this.state.user.name}</span>
<span>{this.state.user.last_name}</span>
...
</div>
);
},
onChange: function() {
this.setState({
user: UsersStore.findUser(this.props.userId)
});
}
});
最后还有UsersStore**:
module.exports = Reflux.createStore({
listenables: [Actions],
users: [],
getUser: function(userId){
return Api.get(url/userId)
.then(function(json){
this.users.push(json);
this.triggerChange();
}.bind(this));
},
findUser: function(userId) {
var user = _.findWhere(this.users, {'id': userId});
if(user){
return user;
}else{
this.getUser(userId);
return [];
}
},
triggerChange: function() {
this.trigger('change', this.users);
}
});
除了 UserPopover 组件外,一切都正常工作。
对于每个 PostComponent 正在渲染一个 UserPopOver,它在 willMount 循环中获取数据。
问题是,如果您注意到我在 UserPopover 组件中有这行代码 console.log(i++);,它会一遍又一遍地递增
...
3820
3821
3822
3823
3824
3825
...
清除一个无限循环,但我真的不知道它来自哪里。如果有人可以给我一个提示,我将非常感激。
PS:我已经在 UsersStore 中尝试过这种方法,但是所有 PostComponent 都有相同的“用户”:
...
getUser: function(userId){
return Api.get(url/userId)
.then(function(json){
this.user = json;
this.triggerChange();
}.bind(this));
},
triggerChange: function() {
this.trigger('change', this.user);
}
...
并且在 UserPopover
...
onChange: function(event, user) {
this.setState({
user: user
});
}
...
【问题讨论】:
-
非常感谢@ForceMagic 的评论,现在已经很清楚了!
-
很高兴你喜欢它!在重新整理一些想法的同时,我真的很努力地保留了本质! :)
标签: javascript reactjs react-router refluxjs