代码之家  ›  专栏  ›  技术社区  ›  Avijit Barua

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

  •  0
  • Avijit Barua  · 技术社区  · 6 年前

    {
        "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 属性。所以我需要先检查这个内部对象是否存在。下面给出了我的react本机代码。在本节中,我通过调用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 回复  |  直到 6 年前
        1
  •  1
  •   Avijit Barua    6 年前

    在你最后一次 <View> 我想这就是 t20i 你的财产 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
    

    因此,只有在 属性存在,否则返回 null . 希望这有帮助。

        2
  •  1
  •   bennygenel    6 年前

    无论是在不知道对象上的属性是否存在的情况下重复相同的组件,都可以在检查属性是否存在时简化代码。为此,您可以使用 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>