【问题标题】:handleClick ''TypeError: undefined has no properties'' can't find what's undefinedhandleClick ''TypeError: undefined has no properties'' 找不到未定义的内容
【发布时间】:2021-01-29 05:52:53
【问题描述】:

我试图通过单击发送要删除的行的 _id 的按钮来删除后端中的一行,但我得到这个错误指向按钮的行。我不明白这个“未定义”指的是什么,我错过了什么?

  34 | {
  35 | todos && todos.map((todo) => ([
  36 |   <p key={todo._id} >{todo.content}</p>,
> 37 |   <button key={i++}  id="del"  onClick={() => {this.handleClick(todo._id)}}/>
  38 | ]
  39 | ))
  40 | }

我的handleClick如下:

useEffect(() => {
const handleClick = (todo_id) => {
  const delTodo = async () => {
    const del = await Axios.delete('http://localhost:3001/todo/' + todo_id)
    .then(() => {
      console.log('deletado!!')
    })
  }
}
}, [])

【问题讨论】:

  • 功能组件没有thishandleClick 也应该在效果挂钩之外声明

标签: javascript reactjs jsx


【解决方案1】:

使用handleClick而不是this.handleClick。因为功能组件没有this。并且还声明了函数handleClickoutSide useEffectinside 不需要使用

更新

你声明做很多功能。只需删除delTodo 函数并将异步添加到handleClick

 const handleClick = async (todo_id) => {
    const del = await Axios.delete('http://localhost:3001/todo/' + todo_id)
    .then(() => {
      console.log('deletado!!')
    })
 }

<button key={i++}  id="del"  onClick={() => {handleClick(todo._id)}}/>

【讨论】:

【解决方案2】:

函数组件不使用this(箭头函数也有这个词的问题,请记住)。只是不要使用this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2022-12-27
    • 2012-03-02
    • 1970-01-01
    • 2021-11-03
    • 2021-11-08
    • 2015-04-26
    相关资源
    最近更新 更多