3 回答

TA贡献2037条经验 获得超6个赞
我认为this.state.items((prevList) => [...prevList, newItem])
是错误的。
你可以尝试将其更改为[...this.state.items, newItem]
因为this.state.items
没有功能吗?

TA贡献2039条经验 获得超8个赞
在 react 中基于类的组件中,您需要将函数绑定到类构造函数中的类才能使用 this 关键字。
constructor(props){
super(props);
this.addTodo = this.addTodo.bind(this); // add this line
}
现在你可以在 addTodo 函数中使用 this.setState 了。还有另一种不需要绑定它的方法。您可以使用箭头功能代替普通功能。
addTodo = (event) => { //just modify this line
event.preventDefault();
if (!this.state.text.length) {
return alert("Plese Write a todo");
}
const newItem = {
text: this.state.text,
id: Date.now()
}
this.setState({
items: this.state.items((prevList) => [...prevList, newItem]),
text: "",
});
}
您可以在此处阅读有关常规函数和箭头函数之间差异的更多信息 - https://medium.com/better-programming/difference-between-regular-functions-and-arrow-functions-f65639aba256

TA贡献1798条经验 获得超7个赞
您的代码的问题在于它this.state.items是一个数组,而不是一个接受回调的函数。
this.setState({
items: this.state.items((prevList) => [...prevList, newItem]),
text: "",
});
使用 setter from 时useState,您将当前状态作为回调参数获取,如 中所示setItems(prevList => [...prevList, newItem])。
在基于类的setState中,您在那里获得回调参数,而不是您访问项目的位置。
对于您的代码,您需要:
this.setState(state => (
items: [...state.items, newItem],
text: "",
));
添加回答
举报