簡體   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