为什么我能在React中使用this.state而不需要绑定(bind)或使用箭头函数?

4

我知道箭头函数会继承其父级的上下文,这也是它们在React中如此有用的原因。然而,我有一个React组件:

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';


class AlbumList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            albums: [],

        };

        axios.get('https://rallycoding.herokuapp.com/api/music_albums')
            .then(response => {
                 this.setState({ albums: response.data });
            });
    }


    renderAlbums() {
        const { albums } = this.state;
        const array = albums.map(album => (
                <Text>{album.title}</Text>
            ));

        return array;
    }


    render() {
        return (
            <View>
                { this.renderAlbums() }
            </View>
        );
    }
}

export default AlbumList;

{ this.renderAlbums() } 已经完全正常工作,而无需将 renderAlbums() 转换为箭头函数。我已经阅读了 stackoverflow 上的其他答案,但它们都提到你需要箭头函数或 bind 才能使 this 正常工作。但在我的情况下,它已经很好地运行了,所以为什么要在 ES6 类内部使用箭头函数呢?


我相信这与箭头函数的词法this有关。 - Jack Bashford
@JackBashford 但在这个例子中,我没有使用箭头函数,而且this.state指向构造函数中定义的父类的正确属性。 - samatovS
2个回答

5
如果您使用箭头函数,那么“this”的定义是由函数所在的块定义的。如果您使用“普通”函数,则“this”由调用函数的位置定义。在这种情况下,您从render方法中调用它,因此“this”仍然是组件的实例。如果您尝试从类似于按钮onClick的东西中调用这样的函数,则它将无法找到“setState”,因为“this”基本上是由实际呈现的按钮而不是react类定义的。

0

简单来说,箭头函数从其父级作用域继承this,而常规函数则从调用该函数的位置继承this


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接