【问题标题】:React JS this.state is undefined: Cannot read property 'components' of undefined, where components is a state of the "Board" ComponentReact JS this.state 未定义:无法读取未定义的属性“组件”,其中组件是“板”组件的状态
【发布时间】:2017-04-15 00:39:09
【问题描述】:

我正在制作一个 React 应用程序,我在其中创建、删除和编辑组件(更准确地说是更改它们的文本)。我有一个名为“MyComponent”的基本组件和一个“Board”组件,其中包含在名为“components”的数组中创建的所有“MyComponent”,这是“Board”中的一个状态。删除和添加新组件效果很好。

编辑背后的想法是,当用户点击“编辑”按钮时,状态“正在编辑”变为true,并显示一个文本区域,以便用户输入新文本,当他想点击保存时, “正在编辑”状态返回 false,因此返回到具有名称的 div 的视图。 (名称也应该更新)。

错误名称: 未捕获的类型错误:无法读取未定义的属性“组件”。

代码链接:https://github.com/AndreiEneCristian/ReactComponents/blob/master/EventHandl2.html

由于我不知道的原因,每当我尝试保存已编辑的组件,从而更改其文本并返回“MyComponent”中的 renderNormal 函数时,浏览器都会给我错误“无法读取属性'组件'(这是未定义的状态)。我试图在控制台中打印一些行,出于调试原因,数据得到了正确处理(意味着'MyComponent'的状态成功更改为false,newText保存在“newText”变量中)但它崩溃了,因为“this.状态”未定义。

控制台错误将我指向这一行:“var arr = this.state.components;”在函数中:

updateComponent: function(newText, i) {
        console.log(this.state);
        var arr = this.state.components;
        arr[i] = newText;
        this.setState({components: arr});
        },

注意:this.state 是未定义的,这就是它背后的问题。我该如何解决这个问题?

【问题讨论】:

  • updateComponentText={this.updateComponent.bind(this)}

标签: javascript reactjs


【解决方案1】:

你必须绑定你作为prop传递的函数

<MyComponent key={i} index={i} updateComponentText={this.updateComponent.bind(this)} deleteFromBoard={this.removeComponent}>
   {text}
</MyComponent>);

【讨论】:

  • 非常感谢。这完全解决了它。由于我在 React 中相对较新并且不太了解绑定的所有内容以及为什么有时需要绑定,您能否建议我提供一个链接,其中包含一个对绑定进行适当概述的教程?
  • @AndreiEne 绑定不是 React 特定的。是JS。 developer.mozilla.org/en/docs/Web/JavaScript/Reference/… 它返回一个新函数,其上下文绑定到包含函数(或类)。您应该在类的构造函数中执行this.updateComponent = this.updateComponent.bind(this),这样就不会在每次渲染时都创建一个新函数,并且只创建一次,或者只使用 es6 箭头函数:() =&gt; {}
猜你喜欢
  • 2019-10-23
  • 2020-11-10
  • 1970-01-01
  • 2023-04-08
  • 2018-01-25
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
相关资源
最近更新 更多