javascript - 类型错误 : this is undefined; can't access its "props" property

标签 javascript reactjs

我的待办事项应用程序是这样的......并且......我正在尝试从列表中删除特定的待办事项。我正在从子组件调用一个函数,将另一个函数作为 Prop 传递。问题是,每当我调用子组件中的函数时,它都无法访问父组件中的 Prop ,这也是一个函数。我尝试“绑定(bind)”在父组件中调用的 map 函数。但还是徒劳。 我该如何解决这个问题或者有没有更好的方法来删除待办事项?需要帮忙! 提前致谢!

Here is the snapshot of the error

class Todo extends Component {

//initializing state
constructor(props) {
super(props);
this.state = {
  todoList: ['wash clothes', 'water the garden', 'buy some flowers', 'something else!']
 }
}

//rendering and cycling through the data (toodoList)
render() {
var todoList = this.state.todoList;
todoList = todoList.map(function(item, index) {
  return(
    <TodoItem item={item} onDelete={this.handleClick.bind(this)} key={index} />
  );
}, this);

return(
  <div className="component-body">
    <AddItem />
    <ul>
      {todoList}
    </ul>
  </div>
);
  }

  //removing item
 handleClick(item) {
    var updatedList = this.state.todoList.filter(function(val, index){
  return item !== val;
});
this.setState= {
  todoList: updatedList
  }
}
 }
class TodoItem extends Component {
 render() {
  return(
    <li>
     <div>
       <span> {this.props.item} </span>
       <span className="handle-delete" onClick={this.handleClick}> x </span>
     </div>
   </li>
       );
     }
 //Custom function
    handleClick() {
      this.props.onDelete();
   }
 }

最佳答案

你必须使用箭头函数

handleClick = () => {

或者如果你不能使用它, 在方法所在的类中定义一个构造函数,然后在其中: this.handleClick().bind(this)

这样,你引用的this和方法引用的this是一样的。可以说这是你和方法之间的错误沟通:)

关于javascript - 类型错误 : this is undefined; can't access its "props" property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53176571/

相关文章:

javascript - Javascript for 循环的确切执行顺序是什么?

javascript - Spine.js 和 jquerymobile-router

javascript - 滚动到 li 元素 - jquery

reactjs - 在 create-react-app 之后 React npm start 不起作用

javascript - 我可以只设置 html 输入字符串值的特定部分的样式吗?

javascript - 即使向下滚动,如何使 div 高度整个页面

javascript - 当我传递 array 时,它说 "Input data in wrong format for chart type"。 [线形图]

javascript - Ant 设计中可以更改日期选择器的图标吗?

reactjs - 创建 React 应用程序显示 "Cannot use JSX unless the ' --jsx' 标志已提供”

apache - 完全相同的请求向 Postman 返回 200,但向 React App 返回 404