使用内联 html 时,ReactJS 值未存储在 for 循环中

问题描述

这段代码一个小问题(使用 PrimeReact):

    let dropDownoptions = [];
    for(var i = 0; i<this.state.filter_bonus.length;i++){
        var filter_option = this.state.filter_bonus[i];
        dropDownoptions.push(
            <React.Fragment>
            <Dropdown value={filter_option.type.bonus_name} 
                options={this.state.bonus_map} 
                onChange={(e) => this.updateTypeFilteratIndex(e.value,i)} 
                optionLabel="bonus_name" 
                filter showClear filterBy="bonus_name" 
                placeholder="Select a Bonus" />
            <span>
                <InputNumber value={filter_option.value} 
                onValueChange={(e) => this.updateValueFilteratIndex(e.value,i)} 
                mode="decimal" showButtons min={0} max={100} />
            </span>    
            </React.Fragment>
        );
    }

这用于创建多个下拉列表并将值存储在列表状态变量中,以便使用它的索引读取。这是在选择某个选项时调用函数

updateTypeFilteratIndex(val,index){
    let new_arr = [...this.state.filter_bonus];
    console.log(index);
    new_arr[index]['type'] = val;
    this.setState({filter_bonus: new_arr});
}

这是结果,

enter image description here

但这里的问题是,当我选择某个选项时,例如在第一个下拉列表中,for 循环中的值“i”为 0,尽管当 onChange 被触发时 (e) => this.updateTypeFilteratIndex(e.value,i) 值“i”传递将是 1 而不是 0。因此它将引用错误的下拉列表。 这发生在所有下拉列表中,看起来存储在回调中的值是提前一次迭代。这是正常的还是 React 上的错误? 我已经检查了很多次,一切看起来都很好。

解决方法

我遇到了类似的问题。尝试使用 forEach() 而不是使用 for 循环。 例如:

11754943508222875