javascript - 无法访问函数内的状态

标签 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];
}

但是,当我在 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 类之外,但得到了相同的错误。

当我将其放置在 App 中的 render() 之外时,出现了意外 token 错误。

当我在 constructor(props) 中定义 this.state 并将 text() 放置在 constructor 中时>,我得到ReferenceError:找不到变量:文本

最佳答案

您的问题在于范围界定。

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

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

使用箭头函数

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

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

您可以绑定(bind)函数以使用外部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 函数移至渲染函数之外,并将其绑定(bind)到组件 this
  • 您可以在组件类 block 内使用箭头函数,这看起来就像您已将其绑定(bind)到组件的 this
  • 您可以将状态作为参数传递给函数

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

关于javascript - 无法访问函数内的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52894546/

相关文章:

Javascript 到 jquery a document.get 与 child

javascript - PHP 无法通过 $_POST 获取选择信息

javascript - XMLHttpRequest 在 phantomjs 中异步失败

javascript - 在带有 ImageMapster 的区域中使用 JavaScript FOR

javascript - 获取 no-cors 意外的输入结束

node.js - 将 passport-google-oauth 与 react-native 结合使用

javascript - 防止子组件根据父状态的变化重新渲染

javascript - 从 Javascript 日期获取年份

react-native - 如何在上传图像之前在图像选择器中裁剪图像

javascript - 如何在 React Native 中将事件从 iOS 发送到 javascript