如何检查内部对象是否在react native中存在?

时间:2018-10-23 16:01:16

标签: android reactjs react-native

最近我正在做关于本机的项目。但是我面临一个棘手的问题。当我调用API时,有时会得到内部对象,但在少数情况下却没有得到内部对象。 Json格式就像

{
    "status": "ok",
    "response": {
        "player": {
            "pid": 43332,
            "title": "Abdur Razzak",
            "short_name": "Abdur Razzak",
            "first_name": "Abdur",
            "last_name": "Razzak",
            "middle_name": "",
            "birthdate": "1982-06-15",
            "birthplace": "",
            "country": "bd"
        },
        "batting": {
            "test": {
                "matches": 13,
                "innings": 22,
                "notout": 6,
                 ........
            },
            "odi": {
                "match_id": 0,
                "inning_id": 0,
                "matches": 153,
                ..............
            },
            "t20i": {
                "match_id": 0,
                "inning_id": 0,
                "matches": 34,
                "innings": 20,
                "notout": 10,
                 .......
            },
            "t20": {
                "match_id": 0,
                "inning_id": 0,
                "matches": 87,
                "innings": 43,
                "notout": 18,
                .......
            },
        }
}

但是有时候对于一些玩家来说,我没有得到内心的东西

          "t20i": {
                    "match_id": 0,
                    "inning_id": 0,
                    "matches": 34,
                    "innings": 20,
                    "notout": 10,
                    "runs": 41,
                    "balls": 74,
                    "highest": "9",
                    ........
                }

由于这个问题,当我编写代码以显示t20i属性的值时出现错误。因此,我需要首先检查此内部对象是否存在。我的本机代码如下。在本节中,我将通过调用api来使用json对象。

export default class ProfileDetails extends Component {
    static propTypes = {
        navigation: PropTypes.object.isRequired
    };

    constructor(props) {
        super(props);
        this.state = {
            matchObject: null,
            loading: true,
            upperBanner: "",
            lowerBanner: ""
        };
    }

    componentDidMount() {
        AsyncStorage.getItem("user")
            .then(response => {
                //alert(JSON.stringify(response))
                const x = JSON.parse(response);

                this.axiosGetRecentMatchDetails(
                    `http://206.189.159.149:8080/com-sweetitech-tigers-0.0.1-SNAPSHOT/api/match/player/profile?access_token=${
                        x.access_token
                        }&client_id=android-client&client_secret=android-secret&id=${
                        this.props.navigation.state.params.pid
                        }`
                );
                axios
                    .get(
                        `http://206.189.159.149:8080/com-sweetitech-tigers-0.0.1-SNAPSHOT/api/banner/specific?access_token=${
                            x.access_token
                            }&client_id=android-client&client_secret=android-secret&pageNumber=10&position=1`
                    )
                    .then(banner => {
                        console.log(banner);
                        this.setState({
                            upperBanner: banner.data.image.url
                        });
                    });
                axios
                    .get(
                        `http://206.189.159.149:8080/com-sweetitech-tigers-0.0.1-SNAPSHOT/api/banner/specific?access_token=${
                            x.access_token
                            }&client_id=android-client&client_secret=android-secret&pageNumber=10&position=2`
                    )
                    .then(banner => {
                        console.log(banner);
                        this.setState({
                            lowerBanner: banner.data.image.url
                        });
                    });

            })
            .catch(() => {
                Alert.alert(
                    "Cannot connect to internal storage, make sure you have the correct storage rights."
                );
            });
    }

    axiosGetRecentMatchDetails = async urlvariable => {
        axios
            .get(urlvariable)
            .then(response => {
                this.setState(
                    {
                        matchObject: response.data
                    },

                    () => {
                        this.setState({
                            loading: false
                        });
                    }
                );

            })
            .catch(error => {
                if (error.response.status === 401) {
                    getuserdetails()
                        .then(res => {
                            this.setState({}, () => {
                                this.axiosGetRecentMatchDetails(
                                    `http://206.189.159.149:8080/com-sweetitech-tigers-0.0.1-SNAPSHOT/api/match/player/profile?access_token=${
                                        res.access_token
                                        }&client_id=android-client&client_secret=android-secret&id=${
                                        this.props.navigation.state.params.pid
                                        }`
                                );
                            });
                        })
                        .catch(() => {
                            this.setState({
                                loading: false
                            });
                            Alert.alert(
                                "you are being logged out for unavilability, Please log in again!"
                            );
                            this.props.navigation.navigate("LoginPage");
                        });
                } else {
                    this.setState({
                        loading: false
                    });
                }
            });
    };

使用此部分,我打印内部对象的属性。

                     <View
                        style={{
                            flexDirection: "row",
                            paddingTop: 6,
                            paddingBottom: 6,
                            borderTopWidth: 1,
                            borderBottomWidth: 1,
                            borderColor: "#dcdcdc"
                        }}
                    >
                        <Text style={styles.leftRow}>ODIs</Text>
                        <Text style={styles.rowElementText}>{this.state.matchObject.batting.odi.matches}</Text>
                        <Text style={styles.rowElementText}>{this.state.matchObject.batting.odi.innings}</Text>
                        <Text style={styles.rowElementText}>{this.state.matchObject.batting.odi.runs}</Text>
                        <Text style={styles.rowElementText}>{this.state.matchObject.batting.odi.highest}</Text>
                        <Text style={styles.rowElementText}>{this.state.matchObject.batting.odi.run100}</Text>
                        <Text style={styles.rowElementText}>{this.state.matchObject.batting.odi.run50}</Text>
                    </View>

                    <View
                        style={{
                            flexDirection: "row",
                            paddingTop: 6,
                            paddingBottom: 6,
                            borderTopWidth: 1,
                            borderBottomWidth: 1,
                            borderColor: "#dcdcdc"
                        }}
                    >
                        <Text style={styles.leftRow}>T20Is</Text>
                        <Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.matches}</Text>
                        <Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.innings}</Text>
                        <Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.runs}</Text>
                        <Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.highest}</Text>
                        <Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.run100}</Text>
                        <Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.run50}</Text>
                    </View>

但是问题是有时我没有得到内部对象t20i。这样我在打印<Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.matches}</Text>时会出错。因此我需要有条件地检查内部对象t20i是否存在。我尝试了几种情况,但失败了。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

在您的最后一个<View>元素中,我猜这是负责t20i的{​​{1}}属性的元素吗?

state

您可以使它成为一个单独的功能组件,使用条件渲染返回该特定部分吗?像下面一样

    <View 
style={{ flexDirection: "row", paddingTop: 6, paddingBottom: 6, borderTopWidth: 1, borderBottomWidth: 1, borderColor: "#dcdcdc" }} > 
<Text style={styles.leftRow}>T20Is</Text> 
<Text style={styles.rowElementText}{this.state.matchObject.batting.t20i.matches}</Text> 
<Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.innings}</Text> 
<Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.runs}</Text> 
<Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.highest}</Text> 
<Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.run100}</Text> 
<Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.run50}</Text> </View>

在要应用此功能的位置进行条件渲染

    const t20iComponent = () => { return (<View 
style={{ flexDirection: "row", paddingTop: 6, paddingBottom: 6, borderTopWidth: 1, borderBottomWidth: 1, borderColor: "#dcdcdc" }} > 
<Text style={styles.leftRow}>T20Is</Text> 
<Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.matches}</Text> 
<Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.innings}</Text> 
<Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.runs}</Text> 
<Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.highest}</Text> 
<Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.run100}</Text> 
<Text style={styles.rowElementText}>{this.state.matchObject.batting.t20i.run50}</Text> 
</View> ); }

因此,它将仅在该this.state.matchObject.batting.t20i ? t20iComponent ():null 属性存在的情况下呈现该视图,否则将返回state。希望这会有所帮助。

答案 1 :(得分:0)

除了重复相同的组件而不知道对象的属性是否存在外,您还可以在检查属性是否存在时简化代码。为此,您可以使用Object.keys()

样品

  <View>
    {Object.keys(this.state.matchObject.batting).map(key => (
      <View
        style={{
          flexDirection: 'row',
          paddingTop: 6,
          paddingBottom: 6,
          borderTopWidth: 1,
          borderBottomWidth: 1,
          borderColor: '#dcdcdc',
        }}>
        <Text style={styles.leftRow}>{key.toUpperCase()}</Text>
        {Object.keys(this.state.matchObject.batting[key]).map(key2 => (
          <Text style={styles.rowElementText}>
            {this.state.matchObject.batting[key][key2]}
          </Text>
        ))}
      </View>
    ))}
  </View>