简体   繁体   English

向数组添加新元素或更新现有元素(React 状态)

[英]Add a new element to array or update the existing one (React state)

I'm building an expression parser, which has a 2 column interface with textboxes.我正在构建一个表达式解析器,它有一个带有文本框的 2 列界面。 You enter the expression on the left (ex. 1+2 ) and you see the result on the right.您在左侧输入表达式(例如1+2 )并在右侧看到结果。 Expression in each line is added to an array of strings, like so:每行中的表达式都添加到一个字符串数组中,如下所示:

12+3
1-2        --->   ['12+3', '1-2', 44+2']
44+2

Now, I want to parse each expression with a function and pass it to another array (React state), which contains results:现在,我想用一个函数解析每个表达式并将其传递给另一个数组(React 状态),其中包含结果:

['12+3', '1-2', 44+2'] --> [15, -1, 46]

This is the code (it runs every time the left textbox value changes):这是代码(每次左侧文本框值更改时都会运行):

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));
});

I would like the results to be up-to-date with expressions, so that when one of them changes the result of this expression is updated:我希望结果与表达式是最新的,以便当其中之一更改时,此表达式的结果会更新:

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
]

Unfortunately, currently, a new element is added to the results array once I change the previous expression.不幸的是,目前,一旦我更改了先前的表达式,就会将一个新元素添加到结果数组中。

New elements are added because you keep adding it to state by concat = [...results, parsed];添加新元素是因为您不断通过concat = [...results, parsed];将其添加到 state concat = [...results, parsed]; Try this.尝试这个。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM