繁体   English   中英

无法访问函数内的状态

[英]Cannot access State inside Function

我正在为我的应用程序使用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()外面时,我收到了unexpected token错误。

当我定义this.state一个内部constructor(props)和放置text()的内部constructor ,我得到ReferenceError: Can't find variable: text

你的问题是范围。

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函数移动到render函数之外,并将其绑定this组件。
  • 您可以在组件类块中使用箭头函数,这看起来就像是将它绑定到组件的this
  • 您可以将状态作为参数传递给函数

...而且我确信还有其他几种方法可以解决这种问题。 你只需要当你使用组件的知道this或其他一些this

这里有几个问题。 首先,您需要将text函数绑定到构造函数中的类。 您还需要将text函数移出render方法并将其作为类方法添加(函数名前面没有function ):

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

export default class App extends React.Component {

  constructor () {
    super();
    this.state = {
      foo: 'ABC',
      bar: {
        'ABC': [
          '...',
          '...',
          '...'
        ]
      }
    };
    this.text = this.text.bind(this);
  }

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM