【菜鳥搭建react項目之路13】【react】Cannot read properties of undefined (reading 'props')


  • 報錯:Cannot read properties of undefined (reading 'props')

  • 原因:點擊按鈕調用父組件的add方法控制台報錯,錯誤發生在子向父傳值(子組件修改父組件的值)的過程中。是this指向不正確導致。


錯誤代碼:

子組件代碼

 

這里發現this打印出來是undefined

 

解決:有兩個辦法可以修改this值

  1. 手動修改函數this值,調用addRecord時使用bind指定this
    <button onClick={this.addRecord.bind(this)}>添加</button>
    addRecord() {
        console.log(this);
        this.props.add();
      }

     

  2. addRecord使用箭頭函數,讓函數的this繼承自子組件(AppForm)
    <button onClick={this.addRecord}>添加</button>
    addRecord = () => {
        console.log(this);
        this.props.add();
      };

     

最后,this打印出來指向AppForm子組件。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM