状态被最新更新的值覆盖

时间:2020-05-19 04:57:53

标签: javascript arrays reactjs react-state

我有下面的函数,其中我正在更新以状态存储的数组,我有9个表,对于每个表,我都调用此函数来检查状态,如果为true,则将其存储在数组。

import Foundation
import SwiftUI

struct MainView: View {

    @State var color = ColorValue(color: UIColor.red)

    var body: some View {
        VStack {
            HStack(spacing: 10) {
                SubView(color: $color)
            }
            .padding(10)
            HStack(spacing: 10) {
                SubView(color: $color)
                SubView(color: $color)
            }
            .padding(10)
            HStack(spacing: 10) {
                SubView(color: $color)
                SubView(color: $color)
                SubView(color: $color)
            }
            .padding(10)
        }
    }

}

struct ShapeView_Previews: PreviewProvider {
    static var previews: some View {
        MainView()
    }
}

并且我正在根据这种状态设置另一个变量,如下所示:

const [projectSpaceTypeWarning, setProjectSpaceTypeWarning] = useState([]);

const handleWarning = (librarySourceTableWarning, status) => {
let spaceTypeWarningCount = [...projectSpaceTypeWarning];
if (status) {
  spaceTypeWarningCount.push(librarySourceTableWarning);
} else {
  spaceTypeWarningCount = spaceTypeWarningCount.filter(
    item => item !== librarySourceTableWarning
  );
 }
setProjectSpaceTypeWarning(spaceTypeWarningCount);
};

这里的问题是我正在使用一个表来更新此状态,该表将 if (projectSpaceTypeWarning.length) { values.spaceType.isInWarningState = true; } 设置为true,并相应地设置该状态,这很好。我剩下的表都将状态发送为false并相应地设置状态。 status状态以某种方式覆盖了状态数组中的false状态。

任何人都可以让我知道如何克服此问题的任何建议或想法。

非常感谢。

1 个答案:

答案 0 :(得分:0)

我已经通过使用以下代码解决了这个问题

    const handleWarning = (librarySourceTableWarning, status) => {
    let spaceTypeWarningCount = projectSpaceTypeWarning; // changes at here
    if (status) {
      spaceTypeWarningCount.push(librarySourceTableWarning);
    } else {
      spaceTypeWarningCount = spaceTypeWarningCount.filter(
        item => item !== librarySourceTableWarning
      );
    }
    setProjectSpaceTypeWarning(spaceTypeWarningCount);
   };