【问题标题】:TypeError: this.props.* is not a function (even with binding)TypeError: this.props.* 不是函数(即使有绑定)
【发布时间】:2018-07-09 13:57:39
【问题描述】:

我不断收到以下错误:

TypeError: this.props.onDelete 不是函数

我在 render() 中的函数上有 .bind(this),但这个错误似乎一直在发生,我不知道为什么。以下是相关代码:

App.js

import React, {Component} from 'react';
import Todos from './Components/Todos';

class App extends Component {

  deleteTodo(id) {
    let todos = this.state.todos;

    for (let i = 0; i < todos.length; i++) {
      if (todos[i].id === id) {
        todos.splice(i, 1);
        break;
      }
    }

    this.state.todos = todos;
  }

  render() {


    return (<div className="App">
      <h1>React Todo App</h1>

      <AddTodo/>
      <Todos todos={this.state.todos} onDelete={this.deleteTodo.bind(this)}/>
    </div>);
  }
}

export default App;

Todos.js

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

class Todos extends Component {

  delete(id) {
    this.props.onDelete(id);
  }

  render() {

    let todoItems = '';

    if (this.props.todos) {

      todoItems = this.props.todos.map(todo => {
        return (<Todo id={todo.id} name={todo.name})></Todo>)
      });
    }

    return (<ul class="todos" onDelete={this.props.onDelete.bind(this)}>{todoItems}</ul>);
  }
}

export default Todos;

Todo.js

import React, {Component} from 'react';

class Todo extends Component {

  delete(id) {
    this.props.onDelete(id);
  }

  render() {
    return (<li class="todo" id={this.props.id}>{this.props.name}
      <a onClick={this.delete.bind(this, this.props.id)} class='remove-button' href='#'>X</a>
    </li>)
  }

}

export default Todo;

错误似乎发生在 Todo.js 中,代码如下 sn-p:

delete(id) {
    this.props.onDelete(id)    // Error
}

编辑:为上下文添加了更多代码

【问题讨论】:

  • 恐怕你没有展示足够的代码。我的猜测是您的li 创建是在map 回调或类似的回调中并以这种方式丢失this,但是...请用minimal reproducible example 更新您的问题以证明问题,理想情况下是 runnable 一个使用堆栈片段([&lt;&gt;] 工具栏按钮)。 Stack Snippets 支持 React,包括 JSX; here's how to do one.
  • 你能检查一下上面的网址吗,因为你会知道stackoverflow.com/a/31141861/8574868
  • Tholle 下面的回答是正确的(如果不是 the 问题,那肯定是 a 问题,而且很可能是 the 问题),但如果有更多的上下文,我们可能会提出更好的方法。
  • @T.J.Crowder 你说得对,我是通过
      而不是 传递 onDelete。我没有在我的原始帖子中包含 map() 。我已经编辑了帖子,所以你可以看到我的错误。
    • 请仔细阅读上面我喜欢的两件事,minimal reproducible example 和 how to do a React Stack Snippet。您上面的“sn-ps”不可运行,它们应该只是代码块。但是提供一个可运行的 sn-p following those instructions 会有很大帮助。

    标签: javascript reactjs react-props


    【解决方案1】:

    通过编写this.delete(this.props.id).bind(this),您调用的是您的this.delete 函数,而不是为onClick 提供函数引用。

    你可以这样写:

    onClick={this.delete.bind(this, this.props.id)}
    

    或者使用箭头函数:

    onClick={() => this.delete(this.props.id)}
    

    【讨论】:

    • 很抱歉没有在原始帖子中添加更多上下文,我已经编辑了帖子以添加更多上下文代码。我相信我的问题是在 Todos.js 中,我没有通过 元素传递 onDelete,而是通过
        元素传递它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      相关资源
      最近更新 更多