Javascript ReactJs上的无限循环渲染组件
我面临一个无限循环问题,我看不出是什么触发了它。这似乎是在渲染组件时发生的 我有三个组成部分,组织如下:Javascript ReactJs上的无限循环渲染组件,javascript,reactjs,react-router,refluxjs,Javascript,Reactjs,React Router,Refluxjs,我面临一个无限循环问题,我看不出是什么触发了它。这似乎是在渲染组件时发生的 我有三个组成部分,组织如下: TimelineComponent |--PostComponent |--UserPopover 时间组件网: React.createClass({ mixins: [ Reflux.listenTo(TimelineStore, 'onChange'), ], getInitialState: function() {
TimelineComponent
|--PostComponent
|--UserPopover
时间组件网:
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)
});
}
});
除了UserPopover组件外,所有功能都正常工作
对于每个PostComponent,正在呈现一个UserPopOver,用于获取willMount循环中的数据
问题是,如果您注意到我有这行代码console.log(I++)在UserPopover组件中编写>代码,该代码一次又一次递增
...
3820
3821
3822
3823
3824
3825
...
Clearl是一个无限循环,但我真的不知道它来自哪里。如果有人能给我一个提示,我将非常感激
PS:我已经在用户存储中尝试过这种方法,但是所有后组件都有相同的“用户”:
在用户Popover中
...
onChange: function(event, user) {
this.setState({
user: user
});
}
...
您可以这样做:
TimelineComponent
|--PostComponent
|--UserPopover
UserPopover只需侦听更改并更新自身
UserPopover在store中侦听更改,store保存哪些用户的数据应该在popover中以及更改更新本身。还可以将坐标发送到渲染的位置。无需为每篇文章创建Popover。因为你的文章是异步获取的,我相信当你的UserPopover组件执行它的组件时,props.userId是未定义的,然后你调用UsersStore.findUser(this.props.userId),在UserStore中调用getUser,因为它在本地存储中找不到用户
注意,每次getUser的ajax完成时,它都会触发。因此UserPopover组件执行onChange函数,并再次调用UsersStore.findUser。这是一个无止境的循环
请在UserPopover的组件willMount中添加一个console.log(this.props.userId),以了解它是否像我上面所说的那样。我其实不是100%肯定
这是一个所有UserPopover实例共享同一个UserStore的问题,我认为我们应该重新考虑这些组件和存储的结构。但我还没有想出最好的办法 非常感谢@ForceMagic的评论,现在已经非常清楚了!我很高兴你喜欢它!我真的试图在重新组织一些想法时保留精华!:)
...
onChange: function(event, user) {
this.setState({
user: user
});
}
...
TimelineComponent
|--PostComponent
|--UserPopover