为什么我无需绑定或使用箭头功能React就可以使用this.state

sam*_*ovS 4 javascript ecmascript-6 reactjs react-native arrow-functions

我知道箭头函数继承了父级的上下文,这就是为什么它们在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;
Run Code Online (Sandbox Code Playgroud)

并且{ this.renderAlbums() }可以正常工作,而无需转换renderAlbums()为箭头功能。我一直在阅读关于stackoverflow的其他答案,但是它们都提到您需要箭头功能或bind为了this正常工作。但就我而言,它可以正常工作,那么为什么在es6类中使用arrow函数?

Ror*_*ory 5

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