【问题标题】:Cannot read property 'XYZ' of undefined – Binding Issue [duplicate]无法读取未定义的属性“XYZ” – 绑定问题 [重复]
【发布时间】:2019-06-15 19:00:53
【问题描述】:

我刚刚开始学习 react,马上就遇到了绑定问题。

我总是得到“无法读取未定义的属性'onDismiss'”-错误,我不知道如何解决这个问题。尝试了多种方法来正确绑定“this”,但没有任何效果。

这是我的应用组件的完整代码:

import React, { Component } from 'react';
import './App.css';

const list = [
{
title: 'React',
url: 'https://reactjs.org/',
author: 'Jordan Walke',
num_comments: 3,
points: 4,
objectID: 0,
}, 
{
title: 'Redux',
url: 'https://redux.js.org/',
author: 'Dan Abramov',
num_comments: 2,
points: 5,
objectID: 1,
},
{
title: 'Reddit',
url: 'https://reddit.com/',
author: 'Crazy Guys',
num_comments: 2000,
points: 3,
objectID: 2,
}, 
];

class App extends Component {

constructor(props) {
super(props);

this.state = {
  list: list,
  list_title: 'Links',
};

this.onDismiss = this.onDismiss.bind(this);
}

onDismiss(id) {
console.log(id)
//const isNotId = item => item.objectID !== id;
//const updateList = this.state.list.filter(isNotId);
}

render() {
return (
  <div className="App">
    <h2>{this.state.list_title}</h2>
    {this.state.list.map(function(item) {
        return (
          <div key={item.objectID}>
            <span>
              <a href={item.url}>{item.title}</a>
            </span>
            <span>
              {item.author}
            </span>
            <span>
              {item.num_comments}
            </span>
            <span>
              {item.points}
            </span>
            <span>
              <button 
                onClick={() => 
                  this.onDismiss(item.objectID)}
                  type="button"
              >
              Dismiss
              </button>
            </span>
        </div>
        );
    })}
  </div>
);
}
}

export default App;

【问题讨论】:

  • 您的地图函数回调没有绑定。请检查重复的帖子
  • 只需将地图内的函数更改为箭头函数。 {this.state.list.map((item) =&gt; { ....... }

标签: reactjs binding create-react-app


【解决方案1】:

这是因为您没有将函数绑定到 onClick 事件处理程序。

onClick={this.onDismiss.bind(this,item.objectID)}

【讨论】:

  • 我愿意,在这里:
  • 好的,那么您可以做的就是将您的地图功能更改为箭头语言。
  • 是的,谢谢,这就是解决方案:)
【解决方案2】:

改变

<h2>{this.state.list_title}</h2>
{this.state.list.map(function(item) { ... }}

<h2>{this.state.list_title}</h2>
{this.state.list.map(item => { ... }}

【讨论】:

  • 我自己试过了,但它会产生同样的错误。我是否还必须更改 onClick 的实现?
  • 已更新,立即查看@mrnb
  • 很好,这行得通。现在我必须处理这个答案,没有得到它;)
  • 基本上 function(item) 为 item 变量创建了一个新范围,因此使 'this' 关键字无用 @mrnb
  • 啊,箭头函数不会创建它,对吧?好的,那很好;)再次感谢。
猜你喜欢
  • 2017-01-30
  • 1970-01-01
  • 2022-06-16
  • 2022-07-28
  • 2022-01-01
  • 2020-02-15
  • 1970-01-01
  • 2021-10-31
相关资源
最近更新 更多