有条件的 if else 列出反应中的数据

Conditional if else list data in react

我有 json 数据,并且在列表中。这里我想用空数据审批条件。

但是我没有成功:

   componentDidMount(){
        this.getJson();
    }

 getJson= () => {

        const url = `https://example.com/priceon?ori=${a}&des=${b}`
        fetch(url)
          ....
    };

render() {
    //here I make a condition if the data exists and does not exist
    if (this.state.results == '') {
        return(
        <View>
            <Text style={{fontWeight:'bold',fontSize:16}}>DATA NULL</Text>
        </View>
        );
    } else {
        return (
        <Container style={styles.container}>
                    <List 
                        keyExtractor = {(item, index)=> index.toString()} 
                        dataArray={this.state.results}
                        renderRow={(results) =>
                        <ListItem>
                            <Body>
                                <CardItem>
                                    <Text>{results.tipe} - {results.service}</Text>
                                </CardItem>
                            </Body>
                        </ListItem>
                    }>

      </Container>
    );
      }
    }

如何制定合适的条件?

如果数据存在则显示,如果为空则显示空数据

如果 API 将 returns 作为数组调用,那么您可以执行 this.state.results.length 检查,也许还有额外的 null 检查。

尝试如下:

render() {
   <>
      {
          this.state.results && this.state.results.length ?
             <Container style={styles.container}>
                 { /* your code */ }
             </Container>
          :
             <View>
                 <Text style={{fontWeight:'bold',fontSize:16}}>DATA NULL</Text>
             </View>
      }
   </>

进一步阅读 Conditional Rendering. Especially the Inline If with Logical && Operator 部分。

下面是代码:)

render() {
//you can use ternary if statement, this is much more better than normal if(s)
return((this.state.results.length)?
    (<View>
        <Text style={{fontWeight:'bold',fontSize:16}}>DATA NULL</Text>
    </View>):
    (<Container style={styles.container}>
                <List 
                    keyExtractor = {(item, index)=> index.toString()} 
                    dataArray={this.state.results}
                    renderRow={(results) =>
                    <ListItem>
                        <Body>
                            <CardItem>
                                <Text>{results.tipe} - {results.service}</Text>
                            </CardItem>
                        </Body>
                    </ListItem>
                }>
  </Container>));
}