【发布时间】:2019-07-24 02:56:34
【问题描述】:
我知道箭头函数会继承父函数的上下文,这就是它们在 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有关。 -
@JackBashford 但在这个例子中我没有使用箭头函数,this.state 指向的是构造函数中定义的父类的正确属性。
标签: javascript reactjs react-native ecmascript-6 arrow-functions