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: "",
));
添加回答
舉報