javascript 无法访问函数内的状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52894546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:02:39  来源:igfitidea点击:

Cannot access State inside Function

javascriptreactjsreact-nativeexpo

提问by Mrigank Pawagi

I am using React Nativefor 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 Expoclient, 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 Appclass, but got the same error.

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

When I placed it outside render()in App, I got an unexpected tokenerror.

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

When I defined this.statewithin a constructor(props)and placed text()within the constructor, I got ReferenceError: Can't find variable: text

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

回答by Sergio Moura

Your problem is scoping.

你的问题是范围界定。

The thisthat 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 txtinto 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 txtfunction to outside of the render function and bind it to the component 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.
  • You can pass the state as a parameter to the function
  • 您可以将txt函数移到渲染函数之外并将其绑定到组件this
  • 您可以在组件类块中使用箭头函数,这看起来就像您已将其绑定到组件的this.
  • 您可以将状态作为参数传递给函数

...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 thisor some other this.

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

回答by Chase DeAnda

A few issues here. First, you need to bind the textfunction to the class in the constructor. You also need to move the textfunction out of the render method and add it as a class method (no functionin front of function name):

这里有几个问题。首先,您需要将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>
    );
  }
}