javascript - 如何使用表单在反应中编辑状态
问题描述
我按照这个 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
所以在我的简单版本中,按下编辑按钮应该将文本道具更改为“编辑”,但它没有做任何事情。
解决方案
看你的状态,应该是this.state.currentItem.text
this.state = {
items: [],
currentItem: {
text: '',
key: '',
},
您可以像这样更新您的状态:
editItem = key => {
console.log(key)
this.setState(prevState=> ({ currentItem: {key, text: 'edit'})
}
推荐阅读
- webpack - 由于 less-loader 错误,无法捆绑 less 文件
- docker - 从 Unix 套接字文件中读取
- php - 我的实时服务器中的 Buddypress 成员区域为空白
- r - 给定一些初始代码,编写 for 循环的问题
- java - 在配置文件中创建地图
- myget - (413) 包裹尺寸太大 - MyGet
- java - SearchView 上的 RecycleView 错误
- python - QScrollArea.ensureWidgetVisible 方法不显示目标小部件
- javascript - 是否可以构造一个对象,以便在请求其键时引发错误?
- node.js - Monk - 查询后数据去哪了?