React + Firebase 组件不会在数据更改时重新渲染(删除)

IT技术 javascript reactjs firebase
2021-05-01 06:02:30

这是一个渲染/性能问题。

我已经使用 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;

非常感谢任何帮助!!

2个回答

你似乎已经明白你需要什么。在您的componentWillMount方法中,您可以注册各种userRef事件。您只需要groupRef使用相同的回调注册事件。每当setState调用组件方法时,React 都会重新呈现,您正在内部执行此操作buildGroupList您只需要buildGroupListgroupRef更新调用

componentWillMount: function() {
        var events = ['value', 'child_removed', 'child_added'];
        var refs = [groupRef, userRef.child(auth.uid).child('groups')];
        var callback = this.buildGroupList;
        refs.forEach(function(ref) {
            events.forEach(function(e) {
                ref.on(e, callback);
            });
        });
    },

我相信这是由于使用.once(). 根据 Firebase 的文档,.once()用于查询数据库位置,而无需附加持久侦听器,例如.on('value', callBack). 但是,当我更改了我调用.once()使用的代码中的实例时.on()(即使我不想在那里附加一个侦听器,而是简单地检索一次数据),所有不稳定的行为都停止了,我的应用程序更新了this.state,组件如下我原本就预料到了。

我唯一能从这次经历中吸取教训的是,.once()它没有按预期/陈述的那样发挥作用,应该使用.on()(加上适当的.off()参考资料)来代替。