【发布时间】:2016-03-05 22:16:54
【问题描述】:
这是一个渲染/性能问题。
我已经使用 Firebase 构建了一个基本的 React 应用程序。它基本上可以工作,但有一个明显的异常行为:渲染并非完全独立发生。
具体来说,我检索用户所属的组列表,并希望能够添加/删除组,从而触发重新渲染。我正在使用 Firebase 的 .on('value')、.on('child_added') 和 .on('child_removed') 函数来绑定对这些事件的引用。
添加和删除组有效,但是组列表消失了(特别是在删除时注意到),我必须单击一个按钮(字面意思是 UI 中的任何按钮)才能将其恢复(它会立即弹出,并带有所有基于用户操作的正确数据)。
所以 - 我显然在某个地方遗漏了一些东西,尽管我一直在测试各种修复程序并且还没有能够理解这个问题。组件是:
主管理组件:
var React = require('react'),
groupRef = new Firebase('http://my-url/groups'), //list of groups
userRef = new Firebase('http://my-url/users'), //list of users
groupListArray = [];
var AdminContainer = React.createClass({
mixins: [ReactFireMixin],
getInitialState: function() {
return {
groups: []
}
},
buildGroupList: function (dataSnapshot) {
groupListArray = [];
var groupList = dataSnapshot.val();
/* The group ids are saved as children in the db
* under users/$userid/groups to reflect which groups a user can
* access - here I get the group ids and then iterate over the
* actual groups to get their names and other associated data under
* groups/<misc info>
*/
for (var key in groupList) {
if (groupList.hasOwnProperty(key)) {
groupRef.child(key).once('value', function(snapShot2) {
groupListArray.push(snapShot2);
});
}
}
this.setState({
groups: groupListArray
});
},
componentWillMount: function() {
userRef.child(auth.uid).child('groups').on('value', this.buildGroupList);
userRef.child(auth.uid).child('groups').on('child_removed', this.buildGroupList);
userRef.child(auth.uid).child('groups').on('child_added', this.buildGroupList);
},
handleRemoveGroup: function(groupKey){
userRef.child(auth.uid).child('groups').child(groupKey).remove();
},
render: function() {
<div id="groupAdminDiv">
<table id="groupAdminTable">
<thead>
<tr>
<th>Group Name</th>
<th>Action</th>
</tr>
</thead>
<GroupList groups={this.state.groups} remove={this.handleRemoveGroup} />
</table>
</div>
}
});
module.exports = AdminContainer;
然后是 GroupList 组件:
var React = require('react');
var GroupList = React.createClass({
render: function() {
var listGroups = this.props.groups.map((group, index) => {
if (group != null) {
return (
<tr key={index} className="u-full-width">
<td>
{group.val().group_name}
</td>
<td>
<button className="button" onClick={this.props.remove.bind(null, group.key())}>Remove</button>
</td>
</tr>
)
} else {
return (
<tr>
<td>You have not added any Groups.</td>
</tr>
)
}
});
return (
<tbody>
{listGroups}
</tbody>
)
}
});
module.exports = GroupList;
非常感谢任何帮助!
【问题讨论】:
标签: javascript reactjs firebase