繁体   English   中英

React Native 中箭头函数和普通函数的区别

[英]Difference between arrow functions and normal functions in React Native

所以直到今天,我一直认为箭头函数是普通 js 函数的一个新的更好的版本。 当我遇到一个问题时,我正在学习如何使用 firestore 存储数据的教程,该问题使我意识到两者不同并且以奇怪的方式工作。 他的代码是这样的:

 //component function Todos() { const [ todo, setTodo ] = useState(''); const ref = firestore().collection('todos'); // ... async function addTodo() { await ref.add({ title: todo, complete: false}); setTodo(''); } // ... }

我的代码如下所示:

 //component const Todos = () => { const ref = firestore().collection('todos'); const [todo, setTodo] = useState(''); const addTodo = async () => { const res = await ref.add({ title: todos, complete: false }); setTodo(''); }; };

现在他的版本有效,而我的没有。 在将我的代码更改为看起来像他的代码后,它起作用了。 但我意识到的奇怪事情是:在单击第一次调用该函数的按钮(使用他的函数)后,我将代码改回我的代码并且它第二次工作了。 我对这两个函数做了一些阅读,但我无法解释为什么会发生这种情况。

箭头函数和普通函数不是等价的。

这是区别:

箭头函数没有自己的this绑定,所以你的this.setState指的是YourClass.setState。

使用普通函数,需要将其绑定到类上,才能获得类的 this 引用。 所以当你调用 this.setState 时,它​​实际上是指 YourFunction.setState()。

示例代码

class FancyComponent extends Component {
    handleChange(event) {
        this.setState({ event }) // `this` is instance of handleChange
    }

    handleChange = (event) => {
        this.setState({ event }) // `this` is instance of FancyComponent
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM