[英]Add a new element to array or update the existing one (React state)
我正在構建一個表達式解析器,它有一個帶有文本框的 2 列界面。 您在左側輸入表達式(例如1+2
)並在右側看到結果。 每行中的表達式都添加到一個字符串數組中,如下所示:
12+3
1-2 ---> ['12+3', '1-2', 44+2']
44+2
現在,我想用一個函數解析每個表達式並將其傳遞給另一個數組(React 狀態),其中包含結果:
['12+3', '1-2', 44+2'] --> [15, -1, 46]
這是代碼(每次左側文本框值更改時都會運行):
const [results, setResults] = useState([]);
expressions?.map(async exp => {
// Custom function that evaluates the expression
const parsed = await parse(exp);
const concat = [...results, parsed];
setResults(concat.filter((item, pos) => concat.indexOf(item) === pos));
});
我希望結果與表達式是最新的,以便當其中之一更改時,此表達式的結果會更新:
Expressions:
[
'10+5',
'5+5', <-- User changes 5 to 3
'3+3'
]
Results:
[
15,
10, <-- Instantly changes to 8 (no new element is added)
6
]
不幸的是,目前,一旦我更改了先前的表達式,就會將一個新元素添加到結果數組中。
添加新元素是因為您不斷通過concat = [...results, parsed];
將其添加到 state concat = [...results, parsed];
嘗試這個。
const [results, setResults] = useState([]);
let concat = []
expressions?.map(async exp => {
// Custom function that evaluates the expression
const parsed = await parse(exp);
concat = [...concat, parsed];
});
setResults(concat);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.