react-native - React Native this .'function' is not a function

标签 react-native

我正在学习 React Native 和 Redux,这里有很多类似的问题,但我很难与我的问题联系起来。

当我在另一个方法中调用一个方法时,它一直返回给我 this.'some function' 不是一个函数,我真的不知道该怎么做。

这是我的一些代码..

import React, { Component } from 'react';
import { Text, StyleSheet, ScrollView } from 'react-native';
import { connect } from 'react-redux';
import Panel from '../components/panel';

class Orders extends Component {
    displayItems(obj) {
        console.log('itemArr', obj);
        return obj.items.map(function(item){
           return (<Text>{item.quantity + ' ' + item.name}</Text>)
        });
    }

    renderContents() {
        console.log('orders', this.props.orders);
        if (!this.props.orders) {
            return <Text>Loading...</Text>;
        }
        return this.props.orders.map(function(order) {  
                return (
                    <Panel title={order.id} key={order.id}>
                        <Text>
                            Item: {this.displayItems(order)}{'\n'}

                        </Text>
                    </Panel>
                );
        });
    }

    render() {
        return(
            <ScrollView style={styles.container}>
                {this.renderContents()}
            </ScrollView>
        );
    }
}

我不确定为什么 render 方法中的函数不会导致任何错误,但我的 renderContents 方法中的函数调用会导致错误。

我感谢任何解决此问题的建议。

最佳答案

这是一个有约束力的问题。 JavaScript 中的函数有自己的 this除非另有明确说明,否则上下文,所以当你这样做时

return this.props.orders.map(function(order) {  
  return (
    <Panel title={order.id} key={order.id}>
      <Text>Item: {this.displayItems(order)}{'\n'}</Text>
    </Panel>);
});
this不是指向您的类,而是指向函数本身。只需执行以下操作
return this.props.orders.map((order) => {  
  return (
    <Panel title={order.id} key={order.id}>
      <Text>Item: {this.displayItems(order)}{'\n'}</Text>
    </Panel>);
});

箭头函数没有自己的上下文,所以这应该适合你。您也可以调用 bind ,但我认为箭头函数解决方案更简单。

关于react-native - React Native this .'function' is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43218451/

相关文章:

reactjs - React-axios-middleware promise 处理

android - ScrollView 不适用于 android 像素模拟器,但它适用于 ios 设备和模拟器

java.lang.RuntimeException : Unable to instantiate application com. todos.MyApplication : java. lang.ClassNotFoundException 异常

javascript - 如何在 React Native 上设置 Slider 的样式

javascript - react native : How do payments among users in mobile marketplace app work?

listview - React Native - 在特定位置滚动 ListView - 以编程方式

javascript - 重置主屏幕的导航堆栈(React Navigation 和 React Native)

javascript - 条件 CSS 不在 React Native 中呈现

Android 不使用设备宽度和高度创建运行时 View

android - 无法让 React Native 在 Ubuntu 上运行