【问题标题】:Why I'm able to use this.state without having to bind or use arrow function React为什么我能够使用 this.state 而无需绑定或使用箭头函数 React
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    箭头函数从其父作用域继承this,但常规函数从调用函数的位置继承this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-25
      • 2021-11-07
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多