Javascript - 迭代期间使用值而不是引用

标签 javascript scope

以这个简单的方式在 ReactJs 中创建列表组件:

for (var key in this.props.code_values)
        {
            var current = this.props.code_values[key];
            var current_value = current.value;
            drop_choices.push(<ListItem
                                button
                                key = { current.id }
                                onClick = {(event) => this.makeSomethingWithValue(current_value)}
                              >
                                { current.value }
                              </ListItem>);
        }

问题是 current_value 是在 Click 上计算的,因此它将始终等于迭代的最后一个 current_value。

例如:

code_values = [ { id : 1, value : 1}, { id : 2, value : 2} ]

点击“1”将得到“2”。

我们不是“创建”html satic 代码,而是一个组件,并且 OnClick 不是在此迭代期间“创建”为属性,而是仅在 onClick 事件之后“处理”。

最佳答案

这是 var 的作用域问题,请尝试使用 letconst 代替

for (let key in this.props.code_values)
    {
        const current = this.props.code_values[key];
        const current_value = current.value;
        drop_choices.push(<ListItem
                            button
                            key = { current.id }
                            onClick = {(event) => this.makeSomethingWithValue(current_value)}
                          >
                            { current.value }
                          </ListItem>);
    }

关于Javascript - 迭代期间使用值而不是引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53045064/

相关文章:

javascript - Ant Design Popconfirm - 将预选按钮更改为取消

c - 如何在机器级别或内存级别的编译器中实现变量的范围

c++ - 当 Injected-Class-Name 发生时会发生什么? (C++)

javascript - 在 ngFor 循环中选择变量键

javascript - Ext js 6读取变量定义

C++ "Variable not declared in this scope"- 再次

python - “finally”有多深?

spring - 如何使用事务范围的持久化上下文进行非事务性读取查询?

javascript - reCAPTCHA v3 和 vue-recaptcha-v3 (v1.8.0) 的 fetch API 验证不断失败

javascript - 通过右键单击保护图像不被下载