亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將函數掛鉤轉換為類狀態

如何將函數掛鉤轉換為類狀態

慕森卡 2022-10-13 16:15:45
我正在嘗試在功能組件和基于類的組件中制作待辦事項應用程序;在函數function addTodo(event) {    event.preventDefault();    if (!text.length) {      return alert("Plese Write a todo");    }    const newItem = {      text: text,      id: Date.now(),    }    setItems(prevList => [...prevList, newItem])    console.log(newItem);    setText("");    inputRef.current.focus();  }但是在課堂上,當我設置項目的狀態時,它給了我一個錯誤    addTodo(event) {        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: "",        });    }
查看完整描述

3 回答

?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

我認為this.state.items((prevList) => [...prevList, newItem])是錯誤的。

你可以嘗試將其更改為[...this.state.items, newItem]因為this.state.items沒有功能嗎?


查看完整回答
反對 回復 2022-10-13
?
largeQ

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


查看完整回答
反對 回復 2022-10-13
?
元芳怎么了

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: "",

));


查看完整回答
反對 回復 2022-10-13
  • 3 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號