簡體   English   中英

未捕獲的類型錯誤:無法添加屬性 0,object 在 Array.push 不可擴展

[英]Uncaught TypeError: Cannot add property 0, object is not extensible at Array.push

從 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>
)

當您嘗試推送到凍結數組時,您得到的錯誤是:

 const temp = Object.freeze([]); temp.push(42);

您已經證明您將數組作為rows傳遞給DataGrid 顯然, 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>
    )
}

感謝 TJ Crowder 的回答,它幫助我理解了真正的問題不是你要傳遞值的 object,而是原來的 object,因為它是通過引用傳遞的。

所以,當你有錯誤時

object is not extensible at array

解決方案是將原始 object 的值復制到目標,而不僅僅是用等號 (=) 運算符賦值。

例如

targetObject.nodes.map( (newNode: any) => {

    //here I create a new object and enrich it with an array and a boolean
    let newFullNode = Object.assign({}, newNode, {nodes: []  , hasChildren:true}); 
    
    targetObject.nodes.push(newFullNode);
});

我稍后更新了 targetObject,當我更新它時,才收到錯誤,這誤導了我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM