为什么我可以使用 this.state 而无需绑定或使用箭头函数 React
Why I'm able to use this.state without having to bind or use arrow function React
我知道箭头函数继承父级的上下文,这就是它们在 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()
转换为箭头函数。我一直在阅读有关 Whosebug 的其他答案,但他们都提到您需要箭头函数或 bind
才能使 this
正常工作。但在我的例子中它工作正常,所以为什么在 es6 class?
中使用箭头函数
如果您使用的是箭头函数,那么 "this" 是由定义该函数的块定义的。如果您使用的是 "normal" 函数,那么 "this" 是由调用函数的位置定义。在这种情况下,您从 render 方法中调用它,因此 "this" 仍然是组件的一个实例。如果您尝试从按钮 onClick 之类的东西调用类似的函数,那么它将无法找到 "setState",因为 "this" 基本上是由实际呈现的按钮定义的,而不是由反应 class 定义的。
只是 箭头函数 从其父级范围继承 this
,但常规函数从调用函数的地方继承 this
我知道箭头函数继承父级的上下文,这就是它们在 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()
转换为箭头函数。我一直在阅读有关 Whosebug 的其他答案,但他们都提到您需要箭头函数或 bind
才能使 this
正常工作。但在我的例子中它工作正常,所以为什么在 es6 class?
如果您使用的是箭头函数,那么 "this" 是由定义该函数的块定义的。如果您使用的是 "normal" 函数,那么 "this" 是由调用函数的位置定义。在这种情况下,您从 render 方法中调用它,因此 "this" 仍然是组件的一个实例。如果您尝试从按钮 onClick 之类的东西调用类似的函数,那么它将无法找到 "setState",因为 "this" 基本上是由实际呈现的按钮定义的,而不是由反应 class 定义的。
只是 箭头函数 从其父级范围继承 this
,但常规函数从调用函数的地方继承 this