首页 > 解决方案 > 如何使用表单在反应中编辑状态

问题描述

我按照这个 React 教程学习了如何创建一个简单的 toDo-App。现在我想修改这个应用程序并添加一个“编辑”功能。

我尝试使用 this.setState 编辑状态,但 console.log 显示Uncaught TypeError: Cannot read property 'text' of undefined

我的构造函数:

constructor() {
    super()
    this.state = {
      items: [],
      currentItem: {
        text: '',
        key: '',
      },
    }
  }

我当前的编辑功能:

editItem = key => {
  console.log(key)
  console.log(this.state.text)
  this.setState({
    text: "edit"
  })
}

正确的密钥被记录,但没有其他工作。console.log(this.state.text)返回undefined

所以在我的简单版本中,按下编辑按钮应该将文本道具更改为“编辑”,但它没有做任何事情。

标签: javascriptreactjsstate

解决方案


看你的状态,应该是this.state.currentItem.text

this.state = {
      items: [],
      currentItem: {
        text: '',
        key: '',
      },

您可以像这样更新您的状态:

editItem = key => {
  console.log(key)
  this.setState(prevState=> ({ currentItem: {key, text: 'edit'})
}

推荐阅读