我在应用程序中使用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>
        );
    }
}

我try 将text()函数放在App类之外,但得到了相同的错误.

当我把它放在Apprender()之外时,我得到了一个unexpected token错误.

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

推荐答案

你的问题是范围界定.

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

有几种方法可以解决这个问题.以下是一些:

Use arrow functions

您可以将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

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

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

Other approaches

  • 可以将txt函数移动到渲染函数的外部,并将其绑定到组件this.
  • 您可以在组件类块中使用箭头函数,这看起来像是将其绑定到组件的this.
  • 可以将状态作为参数传递给函数

...我相信还有其他几种方法可以纠正这种行为.你只需要知道什么时候使用组件的this或其他this.

React-native相关问答推荐

哪个版本的@stripe/stripe-react-native 模块支持 react native 0.62.0 typscript 模板?

我如何限制 FlatList 中的元素并增加负载?

react native条件渲染

React native flexbox - 如何做 percentages || columns || responsive || grid etc

TypeError:undefined is not an object(判断'navigator.geolocation.requestAuthorization')

react-native android中出现此问题Cannot convert argument of type class org.json.JSONArray的原因是什么?

React-Native 应用程序的 Jest 测试 Animated.View

React native base headers for ios not found

更改默认的 React Native 下拉箭头图标

React Native ScrollView 在snapping后重新回到顶部

React-Native: measure测量一个视图

react-native run-android 在设备上构建旧版本的代码

有react-native复选框的例子吗?

在 React Native 视图上强制 onLayout

删除某些屏幕的顶部导航栏

如何将样式传递给 React-Native 中的容器组件

ReactNative TextInput 不可见 iOS

使用 React Native 运行多个 iOS 模拟器?

Super expression must either be null or a function, not undefined

保存时 Visual Studio 代码格式化失败