从Firebase拉取数据push数组时报Cannot add property 0对象不可扩展错误
问题原因
- 你将直接定义在组件内的普通数组
temp传递给了MUI的DataGrid组件的rows属性,DataGrid为了避免非受控的意外状态修改,会默认冻结传入的rows数组,使其变为不可扩展对象,因此后续调用temp.push方法时就会抛出该类型错误。 - 除此之外你还存在一个隐藏问题:普通JS变量的修改不会触发React组件重渲染,即便没有报错,表格也不会更新展示最新的Firebase数据。
解决方案
使用React的useState存储列表数据,每次从Firebase拿到新数据时生成新数组更新状态即可,修正后的代码如下:
import { useState, useEffect } from 'react'; // 其余原有导入保持不变 function Room() { const [textInput, setTextInput] = useState(''); // 替换原有的temp普通数组为React状态变量 const [roomList, setRoomList] = useState([]); const handleTextInputChange = (event) => { setTextInput(event.target.value); }; const handleSubmit = () => { console.log('here goes'); if (textInput !== '') { const refer = ref(database, 'rooms/'); push(refer, textInput).then(() => { setTextInput(''); toast.success('Added Successfully!'); }); } }; useEffect(() => { const refer = ref(database, 'rooms/'); // onValue返回取消监听的函数,用于组件卸载时清理避免内存泄漏 const unsubscribe = onValue(refer, (snap) => { // 每次拿到数据时生成全新数组 const newRoomList = []; snap.forEach((child) => { console.log(child.val() + child.key); newRoomList.push({ id: child.key, firstName: child.val() }); }); // 更新状态触发组件重渲染,表格会自动同步最新数据 setRoomList(newRoomList); }); return () => unsubscribe(); }, []); return ( <div> <Grid item xs={12}> <SubCard title="Room List"> <div style={{ height: 400, width: '100%' }}> <DataGrid rows={roomList} {/* 替换为state变量 */} columns={columns} pageSize={5} rowsPerPageOptions={[5]} components={{ Toolbar: CustomToolbar }} /> </div> </SubCard> </Grid> </div> ) }
内容的提问来源于stack exchange,提问作者Ibrahim Tinku
相关产品推荐
相关产品推荐

