[英]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.