【问题标题】:Store items with same keys and different values in react在反应中存储具有相同键和不同值的项目
【发布时间】:2018-08-12 09:22:38
【问题描述】:

我需要在构造函数中定义一个状态变量来存储以下项目:

  1. abc = 123
  2. abc = 456
  3. abc = 349
  4. 定义 = 378
  5. 定义 = 348
  6. xyz = 123
  7. xyz = 234

另外,我需要在变量上使用以下函数:

  1. 插入新项目。示例:abc = 234,xyz = 239
  2. 删除值为 123 的 abc。
  3. 在插入/删除之前搜索项目是否已经存在: if (abc with value 123) 存在于变量中。

有哪些不同的方法可以做到这一点?最好的方法是什么?

到目前为止,我正在做这样的事情

//selectedCars= {} is a dictionary defined in the state contructor of other class

class xyz extends React.Component {
constructor(props) {
    super(props);
}

getMeSomething(car, color, event){
//car can be any car like honda or mercedes
//selected cars is a dictionary that is passed from other class in to this class as props
        var existingValues = []
        if (this.props.selectedCars[car] != undefined) {
            existingValues = this.props.selectedCars[car];
        }
        var indexOfCar = existingValues.indexOf(car);
        if (indexOfCar == -1) {
            if (event.target.checked) {
                existingValues.push(car);
            }
        }
        else if (!event.target.checked) {                 
                existingValues.splice(indexOfCar, 1);
        }
        this.props.selectedCars[car] = existingValues
}

render() {
    return (
        <div style={{ ...}}>
                {
                this.props.cars.map((car, i) => {
                    return <div key={i}><span className="yhn"><label><input type="checkbox" onChange={this.getMeSomething.bind(this, car, this.props.color)} /><span></span></label>{car}</span></div>
                    })
                }
        </div>
    );
}
}

【问题讨论】:

  • 请分享您尝试的代码。
  • @HassanImam 我尝试了类似filteredColumns的字典:{}。但是,后来意识到这不是一个很好的解决方案。
  • 我猜这些是对象,您希望将它们存储在数组中吗?您不能将它们直接存储在具有重复属性名称的状态对象上。
  • 您可以为此使用对象或地图。
  • @WilliamFleming 我已经在上面更新了我现在在我的代码中拥有的内容。因此,正在寻找是否有其他方法可以做到这一点,因为我对 UI 的东西有点陌生,以及这是否会产生良好的性能结果。

标签: javascript reactjs react-native


【解决方案1】:

我建议你使用数组模型。 如果存在,您可以轻松找到其上存储的项目。

看:

abc=[];
abc [0]=123;
abc [1]=456;
//and it is better to add them like below:
abc.push (789);
abc.push (101);

在你必须使用函数索引之前找出你的变量是否存储在 abc 上:

I = abc.indexOf(456); // Returns 1 that means you can find 456 on abc [1]
I2 = abc.indexOf (999); // Returns -1 that means the 999 is not stored on abc yet

而且性能完美,您无需担心搜索问题。

但是,根据您的使用情况,对象或字典可能有用。所以让我知道。

【讨论】:

  • 非常感谢。我已经在上面更新了我现在在我的代码中拥有的内容。因此,正在寻找是否有其他方法可以做到这一点,因为我对 UI 的东西有点陌生,而且这是否会产生良好的性能结果。对于数组操作,或多或少是你说的。但是,我想要的是一个类似存储的东西,其中可以有不同值的相同键。
猜你喜欢
  • 2015-08-14
  • 2014-08-18
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
  • 2013-10-16
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
相关资源
最近更新 更多