【问题标题】:JS/React - cannot read property "X" of undefined, unable to access methodJS/React - 无法读取未定义的属性“X”,无法访问方法
【发布时间】:2018-02-16 12:31:57
【问题描述】:

这里有点 React 菜鸟,我已经搜索了相当多的解决方案来解决这个问题,但我仍然感到困惑。简而言之,我有一个带有数字列表的下拉菜单,通过映射从数组呈现。目的是能够通过单击下拉菜单中的按钮之一来通过 setState 更改“coloursValue”的值。一切都正确呈现,但是当我尝试单击其中一个按钮时,我遇到了错误消息“TypeError:无法读取未定义的属性'changeValue'”。我知道这可能是与范围有关的问题,并且“this”没有正确定义,但 changeValue 绑定在构造函数中。我做错了什么,我该如何纠正?

非常感谢您。

let colours = [1, 2, 3, 4, 5];

let coloursMapped = mapItems(colours, "coloursValue");


function mapItems(input, context) {
  let listItems = input.map(item =>
  <DropdownItem key={item}>
    <button onClick={() => this.changeValue.bind(this)}>
      {item}
    </button>
  </DropdownItem>
  );
  return <DropdownMenu right>
    {listItems}
  </DropdownMenu>
}

class App extends Component {

constructor(props) {
  super(props);

  this.changeValue = this.changeValue.bind(this);
  this.toggle = this.toggle.bind(this);
  this.state = {
    coloursValue: "# of Colours",
    dropdownOpen: [false, false, false]
  };
}

changeValue(value, context) {
  // modify "coloursValue" via setState according to the number 
  // selected via the "onClick" handler in "mapItems"
}

toggle(index) {
  let dropdownState = this.state.dropdownOpen.slice();
  dropdownState[index] = !this.state.dropdownOpen[index];
  this.setState({
    dropdownOpen: dropdownState
  });
}

【问题讨论】:

  • “我做错了什么” 当你以“正常”的方式调用函数时,即foo(),那么this要么指全局对象,要么@ 987654324@ 在严格模式下。因此,当您调用mapItems(colours, "coloursValue"); 时,thisundefined,因此this() =&gt; this.changeValue.bind(this) 中是undefined(顺便说一句,它甚至没有调用this.changeValue)。基本上,您试图在组件实例存在之前引用它。

标签: javascript reactjs reactstrap


【解决方案1】:

因为mapItems存在于类之外,所以它无权访问类作用域来绑定changeValue。将mapItems 移动到App 组件中,它应该可以工作。您还应该将colourscoloursMapped 作为状态移动到App 组件中。

【讨论】:

  • 即使你修复了这个问题,它仍然无法工作,因为&lt;button onClick={() =&gt; this.changeValue.bind(this)}&gt; 该行返回一个新函数而不是调用 this.changeValue
  • 是的,您完全正确,没有浏览所有代码。将 onClick 更改为 &lt;button onClick={this.changeValue}&gt;
  • 非常感谢,感谢您的解释和帮助
猜你喜欢
  • 1970-01-01
  • 2023-03-20
  • 2021-07-12
  • 2016-08-06
  • 1970-01-01
  • 2018-04-06
  • 2021-04-28
  • 1970-01-01
  • 2022-11-17
相关资源
最近更新 更多