javascript - 在 React JSX 中引用 `this`

标签 javascript scope reactjs arrow-functions

我正在 React JSX 中编写一个函数,其中包含需要与 this 对话的回调

    this.socket.on('addWashedMission', washedMission => {
        console.log('onAddWashedMission - %s - %s', washedMission.name, 
            new Date(washedMission.birthtime));

        this.state.washedMissions.filter(function(o) {
            return o.name === washedMission.name;
        }).forEach(function(element, i, arr) {
            // HERE IT IS //
            this.state.washedMissions.state.washedMissions.slice(
                this.state.washedMissions.state.washedMissions.indexOf(element), 1);
        });

        this.state.washedMissions.push(washedMission);
        this.state.washedMissions.sort(function(a,b) {
            return b.birthtime - a.birthtime;
        });

        this.setState({
            washedMissions: this.state.washedMissions
        });
    });

注意到 this.state.washedMissions 了吗?当我在那个回调中时,Firefox 脚本调试器告诉我浏览器不知道 this 是什么,因此我不能以这种方式操作我的数组。

我如何确保 this 在我的回调范围内——请注意,回调是同步的,所以我不担心任何时间问题。

最佳答案

你有

...forEach(function(element, i, arr) {
  this.state.washedMissions.state.washedMissions.slice(
    this.state.washedMissions.state.washedMissions.indexOf(element), 1);
});

您需要提供 thisArg 作为 Array.prototype.forEach 的第二个参数

...forEach(function(element, i, arr) {
  this.state.washedMissions.state.washedMissions.slice(
    this.state.washedMissions.state.washedMissions.indexOf(element), 1);
}, this); // <--- note the `this` after the function() {}

或者您需要一个 arrow function它在词法上绑定(bind)了 this

...forEach((element, i, arr) =>
  this.state.washedMissions.state.washedMissions.slice(
    this.state.washedMissions.state.washedMissions.indexOf(element), 1)
);

或者您可以使用其他答案中提供的 stone-age-slow Function.prototype.bind

关于javascript - 在 React JSX 中引用 `this`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33535983/

相关文章:

reactjs - 使用 Framer Motion 沿路径动画 SVG

javascript - React router 4查询参数示例不起作用

javascript - 如何检测整个表单是否失焦?

javascript - 如何循环遍历 li 的 url 读取部分,然后使用 Jquery 将其作为类添加到 li

javascript - jQuery - 选择值等于的元素

javascript - 在 React 中上传图像和其他文本输入?

javascript - 如何获取java中未定义的语言环境DisplayName

python 3 : UnboundLocalError: local variable referenced before assignment

python - 嵌套函数如何更改其封闭函数的实例变量?

c++ - 命名空间范围内的静态关键字无用?