简体   繁体   English

无法访问函数内的状态

[英]Cannot access State inside Function

I am using React Native for my application, and at one point, I noticed that I have to type this.state.bar[this.state.foo][SOME_NUMBER] every time, within my components. 我正在为我的应用程序使用React Native ,有一次,我注意到我必须每次在我的组件中输入this.state.bar[this.state.foo][SOME_NUMBER]

This works perfectly fine, but I want to make my code cleaner by calling a function instead. 这非常好用,但我想通过调用函数来使代码更清晰。 So, I constructed this: 所以,我构建了这个:

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

However, when I run this in the Expo client, I get the following error: 但是,当我在Expo客户端中运行它时,我收到以下错误:

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

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

Here is my entire code. 这是我的整个代码。

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

I tried placing the text() function outside the App class, but got the same error. 我尝试将text()函数放在App类之外,但是得到了同样的错误。

When I placed it outside render() in App , I got an unexpected token error. 当我将它放在App render()外面时,我收到了unexpected token错误。

When I defined this.state within a constructor(props) and placed text() within the constructor , I got ReferenceError: Can't find variable: text 当我定义this.state一个内部constructor(props)和放置text()的内部constructor ,我得到ReferenceError: Can't find variable: text

Your problem is scoping. 你的问题是范围。

The this that you're trying to access inside the txt() function is pointing to its own this , and not the outer component this . this ,你试图向里面访问txt()函数是指向自己的this ,而不是外部组件this

There are several ways to fix this. 有几种方法可以解决这个问题。 here's a few: 这里有几个:

Use arrow functions 使用箭头功能

You can transform txt into an arrow function to use the outer this : 您可以将txt成箭头功能使用外this

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

You can bind the function to use the outer this 您可以绑定功能使用外this

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


    const txt = _txt.bind(this);

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

You can create an additional variable that points to the outer this 您可以创建一个指向外的额外变量this

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

Other approaches 其他方法

  • You can move the txt function to outside of the render function and bind it to the component this . 您可以将txt函数移动到render函数之外,并将其绑定this组件。
  • You can use an arrow function inside the component class block, which will seem like you've bound it to the component's this . 您可以在组件类块中使用箭头函数,这看起来就像是将它绑定到组件的this
  • You can pass the state as a parameter to the function 您可以将状态作为参数传递给函数

...and I'm sure that there are several other ways to fix this behaviour. ...而且我确信还有其他几种方法可以解决这种问题。 You just need to know when you're using the component's this or some other this . 你只需要当你使用组件的知道this或其他一些this

A few issues here. 这里有几个问题。 First, you need to bind the text function to the class in the constructor. 首先,您需要将text函数绑定到构造函数中的类。 You also need to move the text function out of the render method and add it as a class method (no function in front of function name): 您还需要将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