我知道箭头函数会继承其父级的上下文,这也是它们在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