即使绑定了函数,React中也会出现未定义的错误

时间:2020-09-13 20:10:30

标签: reactjs

我已将此handleRemove绑定到构造函数中,但以下代码由于某些原因无法正常工作

handleRemove()
  {
    //console.log(e.target.value)
    console.log('click')
  }
<button key={index} onClick={this.handleRemove}>X</button>

我得到的错误:

TypeError: Cannot read property 'handleRemove' of undefined

即使我删除绑定并使用箭头功能()=> this.handleRemove(),也遇到相同的错误。有人有解决办法吗?

完整部分:

class ScheduleList extends Component
{
  constructor(props)
  {
    super(props);

    this.state = {
      "actions": [],
      "thingsDue" : []
    }

    this.componentDidUpdate = this.componentDidUpdate.bind(this);
    this.componentDidMount = this.componentDidMount.bind(this);
    //this.handleRemove = this.handleRemove.bind(this);
    
  }

  componentDidMount(e)
  {
    fetch("http://localhost:5000/backend/" + this.props.date).then(res => res.json()).then(resjson => {
      this.setState({actions: JSON.parse(resjson)})
      }).catch(err => console.log(err))

      fetch("http://localhost:5000/backend/due/" + this.props.date).then(res => res.json()).then(resjson => {
      this.setState({thingsDue: JSON.parse(resjson)})
      }).catch(err => console.log(err)) 
  }
  
  componentDidUpdate(prevProps) {
    if (this.props.date !== prevProps.date) 
    {
      fetch("http://localhost:5000/backend/" + this.props.date).then(res => res.json()).then(resjson => {
      this.setState({actions: JSON.parse(resjson)})
      }).catch(err => console.log(err))

      fetch("http://localhost:5000/backend/due/" + this.props.date).then(res => res.json()).then(resjson => {
      this.setState({thingsDue: JSON.parse(resjson)})
      }).catch(err => console.log(err)) 
    }
  }

  handleRemove()
  {
    //console.log(e.target.value)
    console.log('click')
  }

  render()
  {
    let listItems = this.state.actions.map((dic, index) => <li key={index}>{"From " + dic.start.toString() + " - " + dic.end.toString() + ": " +  dic.activity}</li>)
    listItems = listItems.map(function(elem, index) {
      return [elem, <button key={index} onClick={() => this.handleRemove()}>X</button>]
    })

    let dueItems = this.state.thingsDue.map((dic, index) => <li key={index}>{dic.thing_due}</li>)

    let timeSpent = 0;
    for(var index = 0; index < this.state.actions.length; index++)
    {
      timeSpent += (this.state.actions[index].end - this.state.actions[index].start);
    }

    dueItems = dueItems.map(function(elem, index) {
      return [elem, <button key={1000 * index + 1000}>X</button>]
    })


    return (
      <div>
        <ul>
          {listItems}
          
        </ul>
        <p>{"Productive hours: " + timeSpent}</p>
        <b>Things Due</b>
        <ul>
          {dueItems}
        </ul>
      </div>
    )
  }

}

1 个答案:

答案 0 :(得分:0)

您需要使用箭头功能更改handleRemove功能。您可以这样做

handleRemove = e => {
  //console.log(e.target.value)
  console.log('click')
}