我跟随this React Tutorial讨论了如何创建简单的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
因此,在我的简单版本中,按“编辑”按钮应将文本属性更改为“编辑”,但是它什么也没做。
答案 0 :(得分:1)
查看您的状态,应该为this.state.currentItem.text
this.state = {
items: [],
currentItem: {
text: '',
key: '',
},
您可以像这样更新状态:
editItem = key => {
console.log(key)
this.setState(prevState=> ({ currentItem: {key, text: 'edit'})
}
答案 1 :(得分:1)
您的控制台日志错误,应该为let loginDetail = this.constants.getUserDetailsFromToken();
if (!(loginDetail.username == "superadmin@alluremedspa.in")) {
if (loginDetail.user_type == "staff") {
navigation[0].children.forEach(e => {
if (e.id == "Staff") {
e.url = e.url + "/" + loginDetail.id;
console.log("check in e.url", e.url);
}
});
this.navigation = navigation;
this.navigation = [...this.navigation];
}
}
if (loginDetail.username == "superadmin@alluremedspa.in") {
console.log("check in superadmin");
this.navigation = navigation;
this.navigation = [...this.navigation];
}
if (loginDetail.user_type == "customer") {
navigationCustomer[0].children.forEach(element => {
console.log("check in e", element);
if (element.id == "Customer") {
// console.log("check customer login", this.constants.getUserDetailsFromToken(), 'dd', this.constants.loginDetail)
element.url = element.url + "/" + loginDetail.id;
}
});
this.navigation = navigationCustomer;
this.navigation = [...this.navigation];
}
答案 2 :(得分:1)
控制台应为 this.state.currentItem.text
。也许您应该先喝杯咖啡或走一小段路,然后再坐下来编码:)
答案 3 :(得分:0)
您的编辑功能应该看起来像这样。您必须setState整个currentItem状态。
editItem = key => {
this.setState({
currentItem: {
text: 'edit',
key,
}
})
}