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

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

在 React 中使用箭頭函數聲明方法

在 React 中使用箭頭函數聲明方法

慕神8447489 2022-12-09 19:02:07
我正在完成 FreeCodeCamp React 練習,其中有一個簡單的遞增和遞減狀態初始化的計數值。如果我使用傳統函數編寫方法,它工作正常:increment() {  this.setState({    count: this.state.count + 1  });}decrement() {  this.setState({    count: this.state.count - 1  });}reset() {  this.setState({    count: this.state.count = 0  });}   但是如果我使用箭頭函數,它就會停止工作。“重置”按鈕不是重置為零,而是以與“減少”按鈕相同的方式減少值?!斑f增”和“遞減”工作顯然正常。increment = () => {  this.setState({    count: this.state.count + 1  });} decrement = () => {  this.setState({    count: this.state.count - 1  });} reset = () => {  this.setState({    count: this.state.count = 0  });}我在這里遺漏了一個細節。一些同事能告訴我為什么函數表達式在這種情況下不起作用嗎?提前致謝。
查看完整描述

2 回答

?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

箭頭函數表達式是常規函數表達式的語法緊湊替代品,盡管它自己沒有綁定到 this、arguments、super 或 new.target 關鍵字。箭頭函數表達式都適合作為方法,它們不能用作構造函數。請檢查此鏈接



查看完整回答
反對 回復 2022-12-09
?
慕尼黑的夜晚無繁華

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

箭頭函數不同于常規函數


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions


簡而言之,'this' 的值在常規函數和 lambda 函數中是不一樣的。


只是為了增加一點精度,您可能使用了 .bind(),因此,使用了兩個函數(一個常規函數和一個返回 this 的箭頭,并嘗試綁定它們,我們得到:


const f=function() { return this; };

const bf=f.bind({});

console.log(bf()); // correctly binds 'this' to the provided object


const l=()=>this;

const bl=l.bind({});

console.log(bl()); // didn't bind, returned window


查看完整回答
反對 回復 2022-12-09
  • 2 回答
  • 0 關注
  • 180 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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