從 firebase 獲取資料并將資料推送到陣列時出現此錯誤。在這里,當我將 firebase onValue 中的資料推送到此臨時陣列時,我定義了一個臨時陣列我收到此錯誤 Uncaught TypeError: Cannot add property 0, object is not extensible at Array.push。這是我的代碼
function Room() {
const [textInput, setTextInput] = useState('');
const temp = [];
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(refer, (snap) => {
snap.forEach((child) => {
console.log(child.val() child.key);
// I am getting error in this line
temp.push({ id: child.key, firstName: child.val() });
});
});
}, []);
return (
<div>
<Grid item xs={12}>
<SubCard title="Room List">
<div style={{ height: 400, width: '100%' }}>
<DataGrid
rows={temp}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
components={{
Toolbar: CustomToolbar
}}
/>
</div>
</SubCard>
</Grid>
</div>
)
uj5u.com熱心網友回復:
當您嘗試推送到凍結陣列時,您得到的錯誤是:
const temp = Object.freeze([]);
temp.push(42);
您已經證明您正在將陣列傳遞給DataGridas rows。顯然,DataGrid凍結陣列,大概是因為它需要知道它的內容不會改變。
如果要更改這些內容,則需要將其存盤temp在 state 中并在添加后重新渲染;查看***評論(我也重命名temp為dataGridRows):
function Room() {
const [textInput, setTextInput] = useState('');
// *** Store it in state
const [dataGridRows, setDataGridRows] = 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(refer, (snap) => {
snap.forEach((child) => {
console.log(child.val() child.key);
// *** Add to it in state; this will cause a re-render
// so DataGrid picks up the change
setDataGridRows(dataGridRows => [...dataGridRows, { id: child.key, firstName: child.val() }];
});
});
}, []);
return (
<div>
<Grid item xs={12}>
<SubCard title="Room List">
<div style={{ height: 400, width: '100%' }}>
<DataGrid
rows={dataGridRows}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
components={{
Toolbar: CustomToolbar
}}
/>
</div>
</SubCard>
</Grid>
</div>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/333507.html
標籤:javascript 反应 火力基地 Firebase 实时数据库
