【问题标题】:Add a new element to array or update the existing one (React state)向数组添加新元素或更新现有元素(React 状态)
【发布时间】:2020-03-05 15:52:05
【问题描述】:

我正在构建一个表达式解析器,它有一个带有文本框的 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
]

不幸的是,目前,一旦我更改了先前的表达式,就会在结果数组中添加一个新元素。

【问题讨论】:

    标签: javascript arrays reactjs concatenation


    【解决方案1】:

    添加新元素是因为您不断将其添加到状态 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);
    

    【讨论】:

      猜你喜欢
      • 2014-12-03
      • 2021-02-06
      • 2019-03-30
      • 2018-05-03
      • 2012-06-18
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多