我正在嘗試創建一個函式來更新反應功能組件中的物件。我想做的是:
const [content, setContent] = useState({});
const applyContent = (num:number,key:string,val:string) => {
if (content[num] === undefined) {
content[num] = {};
}
content[num][key] = val;
setNewContent(newInput);
}
但是我一直收到一個錯誤,指出內容沒有 num 屬性,在 vanilla JS 中它可以作業,我缺少什么讓它與 react 功能組件一起作業?
uj5u.com熱心網友回復:
組件狀態的 setter 拼寫錯誤。看看下面的代碼。希望這可以幫助。
import React, { useState } from 'react';
import './style.css';
export default function App() {
const [content, setContent] = useState({});
const applyContent = (num, key, val) => {
//gets the appropriate inputs
let updatedContent = content;
let value = {};
value[key] = val;
updatedContent[num] = value; //this inserts a new object if not present ot updates the existing one.
setContent({ ...updatedContent });
};
return (
<div>
<h1>Click buttons to change content</h1>
<p>{JSON.stringify(content)}</p>
<button onClick={(e) => applyContent(0, 'a', 'b')}>Add</button>
<button onClick={(e) => applyContent(1, 'c', 'd')}>Add</button>
<button onClick={(e) => applyContent(0, 'e', 'f')}>Add</button>
</div>
);
}
uj5u.com熱心網友回復:
content 是只讀值。你不能直接改變它。僅使用它來顯示資料或將此資料復制到另一個輔助值。
setContent 是一個設定內容的函式。
設定資料有兩種方式
setContent(value) <-- set directly
setContent(prevState => {
return {
...prevState,
...value
}
})
在第二個示例中,您將使用先前的值,復制它,然后用新值覆寫它。如果您只更新物件或陣列的一部分,這很有用。
如果您正在使用深度嵌套的物件,淺拷貝可能還不夠,您可能需要先深拷貝您的內容值。如果沒有,則使用 prevState 示例僅更新該內容的一部分
const [content, setContent] = useState({});
const applyContent = (num:number,key:string,val:string) => {
const newContent = {...content} // Shallow copy content
if (content[num] === undefined) {
//content[num] = {}; <-- you cant directly change content. content is a readOnly value
newContent[num] = {}
}
newContent[num][key] = val;
//setNewContent(newInput);
setContent(newContent) // <-- use "setContent" to change "content" value
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/357445.html
標籤:javascript 反应 反应功能组件
