为什么onClick按钮告诉我调度不是函数

时间:2019-09-11 12:29:15

标签: javascript reactjs

我有一个onDeleteClick函数,当我尝试单击该函数并发出响应时,它给我一个错误,而不是一个函数,并且表明该错误来自此代码

我将单引号更改为反引号,但仍然得到相同的结果

class Contact extends Component {
  state = {
    showContactInfo: false
  };

  onDeleteClick = (id, dispatch) => {
    dispatch({ type: "DELETE_CONTACT", payload: id });
  };

  render() {
    const { name, id, email, phone } = this.props.contact;
    const { showContactInfo } = this.state;

    return (
      <Consumer>
        {value => {
          const { dispatch } = value;
          return (
            <div className="card card-body mb-3">
              <h4>
                {name}
                <i
                  onClick={() =>
                    this.setState({
                      showContactInfo: !this.state.showContactInfo
                    })
                  }
                  className="fas fa-sort-down"
                  style={{ cursor: "pointer", color: "indigo" }}
                />
                <i
                  className="fas fa-times"
                  style={{ cursor: "pointer", float: "right", color: "blue" }}
                  onClick={this.onDeleteClick.bind(this, id, dispatch)}
                />
              </h4>
              {showContactInfo ? (
                <ul className="list-group">
                  <li className="list-group-item">Email: {email}</li>
                  <li className="list-group-item">Phone: {phone}</li>
                </ul>
              ) : null}
            </div>
          );
        }}
      </Consumer>
    );
  }
}

Contact.propTypes = {
  contact: PropTypes.object.isRequired
};

export default Contact;

我希望onDelete函数能够从列表中删除。

1 个答案:

答案 0 :(得分:0)

在类实例中使用箭头功能时,不必绑定onDeleteClick

此外,您调用onDeleteClick而不是将其分配为回调。

// On given params, return a function
onDeleteClick = (id, dispatch) => () => {
  dispatch({ type: "DELETE_CONTACT", payload: id });
};
class Contact extends Component {
  ...
//                               v Assign as a callback
  onDeleteClick = (id, dispatch) => () => {
    dispatch({ type: "DELETE_CONTACT", payload: id });
  };

  render() {
    const { id , ... } = this.props.contact;
    return (
      <Consumer>
        {value => {
          const { dispatch } = value;
          return (
            <div>
              <h4>
                  ...
                <i
//                                           v No bind needed
                  onClick={this.onDeleteClick(id, dispatch)}
                />
              </h4>
            </div>
          );
        }}
      </Consumer>
    );
  }
}