无法访问功能内部的状态

Mri*_*agi 4 javascript reactjs react-native expo

我正在React Native为我的应用程序使用,有一次,我注意到this.state.bar[this.state.foo][SOME_NUMBER]每次必须在组件中键入内容。

这工作得很好,但是我想通过调用一个函数来使代码更整洁。因此,我构造了这个:

function txt(n){
    return this.state.bar[this.state.foo][n];
}
Run Code Online (Sandbox Code Playgroud)

但是,当我在Expo客户端中运行此命令时,出现以下错误:

TypeError: undefined is not an object (evaluating 'this.state.bar')

This error is located at:
    in App...
    ....
Run Code Online (Sandbox Code Playgroud)

这是我的整个代码。

import React, 
    { Component } 
from 'react';
import { 
     ... 
} from 'react-native';

export default class App extends React.Component {
    state = {
        foo: 'ABC',
        bar: {
            'ABC': [
                '...',
                '...',
                '...'
            ]
        }
    };
    render() {
        function txt(n){
            return this.state.bar[this.state.foo][n];
        }
        return (
            <View>
                ...  
            </View>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试将text()函数放置在App类之外,但遇到相同的错误。

当我将它放在外面render()App,出现了unexpected token错误。

当我定义this.stateconstructor(props),并放置text()内的constructor,我ReferenceError: Can't find variable: text

Ser*_*ura 8

您的问题是范围界定。

this你试图向里面接入txt()功能是指向自己的this,而不是外部组件this

有几种方法可以解决此问题。这里是一些:

使用箭头功能

您可以转换txt为箭头函数以使用外部函数this

render() {
    const txt = (n) => {
        return this.state.bar[this.state.foo][n];
    }
    return (
        <View>
            ...  
        </View>
    );
}
Run Code Online (Sandbox Code Playgroud)

您可以绑定功能以使用外部 this

render() {
    function _txt(n){
        return this.state.bar[this.state.foo][n];
    }


    const txt = _txt.bind(this);

    return (
        <View>
            ...  
        </View>
    );
}
Run Code Online (Sandbox Code Playgroud)

您可以创建一个附加变量,该变量指向外部 this

render() {
    const self = this;
    function txt(n){
        return self.state.bar[self.state.foo][n];
    }
    return (
        <View>
            ...  
        </View>
    );
}
Run Code Online (Sandbox Code Playgroud)

其他方法

  • 您可以将txt函数移到render函数之外,并将其绑定到组件this
  • 您可以在组件类块内使用箭头功能,似乎已将其绑定到组件的this
  • 您可以将状态作为参数传递给函数

...而且我敢肯定还有其他几种方法可以解决此问题。您只需要知道何时使用组件this或其他组件即可this

  • 与之绑定的“问题”就是(甚至为此在render函数中创建函数)是每次组件渲染时都在创建一个新的function元素。这是不要在大型​​函数的render函数内创建函数的原因之一。 (2认同)