【问题标题】:React-Native TypeError: undefined is not an object (evaluating 'this.props.screenProps.cities.map')React-Native TypeError:未定义不是对象(评估'this.props.screenProps.cities.map')
【发布时间】:2019-04-05 12:51:05
【问题描述】:

尝试运行程序时在文件 city.js 中出现上述错误。 city.js 屏幕应显示已从 addCity.js 屏幕添加的所有城市。

我是 react-native 新手,不知道如何正确使用 props 和引用。对此的任何帮助将不胜感激。谢谢

city.js:

import React from 'react';
import {
    View,
    Text,
    StyleSheet,
    ScrollView,
    TouchableWithoutFeedback
} from 'react-native';

import { colors } from '../theme'

export default class Cities extends React.Component {
    static navigationOptions = {
        title: 'Cities',
        headerTitleStyle: {
            color: 'white',
            fontSize: 20,
            fontWeight: '400'
        }
    }
    viewCity = () =>{

    }

    render(){

        return (

            <ScrollView>
                        <View>
                        {

                            this.props.screenProps.cities.map((city, index) => (
                                <View>
                                    <TouchableWithoutFeedback onPress={() =>this.viewCity(city)}>
                                        <View style={styles.cityContainer}>
                                        <Text style={styles.city}>{city.city}</Text>
                                        <Text style={style.country}>{city.country}</Text>

                                        </View>

                                    </TouchableWithoutFeedback>

                                </View>
                                ))
                        }
                        </View>
            </ScrollView>

        )
    }
}

const styles = StyleSheet.create({
    cityContainer: {
        padding: 10,
        borderBottomWidth: 2,
        borderBottomColor: colors.primary
    }
})

【问题讨论】:

  • 先检查this.props.screenProps.cities不等于null
  • 数组为空。我以前用这个 if 语句 if(this.props.screenProps.cities &amp;&amp; this.props.screenProps.cities.length) 来检查

标签: react-native undefined typeerror


【解决方案1】:

您应该使用loadsh,因为它会处理像这样的 null 或未定义的对象或数组

首先安装lodash

npm i lodash

然后像这样使用它

import _ from 'lodash'

const cities = _.get(this.props.screenProps, 'cities.map', [])

if(_.size(cities) > 0){
// do something
}

Lodash 是一个值得推荐的 JavaScript 实用程序库。

【讨论】:

    猜你喜欢
    • 2021-11-09
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    相关资源
    最近更新 更多