首页 > 解决方案 > 无法访问函数内部的状态

问题描述

我正在React Native为我的应用程序使用,并且在某一时刻,我注意到我this.state.bar[this.state.foo][SOME_NUMBER]每次都必须在我的组件中输入。

这工作得很好,但我想通过调用一个函数来使我的代码更干净。所以,我构建了这个:

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

但是,当我在Expo客户端运行它时,我收到以下错误:

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

This error is located at:
    in App...
    ....

这是我的整个代码。

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>
        );
    }
}

我尝试将text()函数放在App课堂之外,但得到了同样的错误。

当我把它放在外面render()App,我得到了一个unexpected token错误。

当我this.state在 a中定义constructor(props)并放置text()在 中时constructor,我得到了ReferenceError: Can't find variable: text

标签: javascriptreactjsreact-nativeexpo

解决方案


你的问题是范围界定。

this您试图在函数内部访问的是txt()指向它自己的this,而不是外部组件this

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

使用箭头函数

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

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

您可以绑定函数以使用外部this

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


    const txt = _txt.bind(this);

    return (
        <View>
            ...  
        </View>
    );
}

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

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

其他方法

  • 您可以将txt函数移动到渲染函数之外并将其绑定到组件this
  • 您可以在组件类块内使用箭头函数,这看起来就像您已将其绑定到组件的this.
  • 您可以将状态作为参数传递给函数

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


推荐阅读