【问题标题】:add a condition according to the presence of a database data根据数据库数据的存在添加条件
【发布时间】:2021-05-06 17:55:46
【问题描述】:

我有一个要在其中添加图像的列表。 基本上我的代码运行良好,不幸的是我使用的 API 数据库发生了变化......我的数据库中的一些产品没有图像,所以当我调用有问题的线路时它给了我一个错误...... 所以,我想创建一个条件:如果数据库中有相关产品的图像,我希望它显示出来

图片来源={{uri: URL + item.photo.1.url}}

否则我希望它是一个预设的标志。

我是这样做的:

 <ListItem.Content style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                        {item.photo !== null && item.photo > 0 ? (
                          <Image 
                            source={{uri: URL + item.photo._1_.url}}
                            style={{ width: 25, height: 25}}/> 
                        ) : (
                          <Image 
                            source={require('../../../assets/images/logo.png')}
                            style={{ width: 25, height: 25}}
                          />
                        )};
                        <ListItem.Title style={{width: '65%', fontSize: 16}}>{ ( item.name.length > 20 ) ? item.name.substring(0, 20) + ' ...'  :  item.name}</ListItem.Title>
                        <ListItem.Subtitle style={{ color: '#F78400', position: "absolute", bottom: 0, right: 0 }}>{item.cost}{i18n.t("products.money")}</ListItem.Subtitle>
                      </ListItem.Content>

但我有 2 个错误:

undefined 不是一个对象(评估 'item.photo.1.url')

[未处理的承诺拒绝:错误:必须呈现文本字符串 在一个组件中。]

向您展示数据的外观:

以及该屏幕的完整代码:

export default class Products extends Component {
  constructor(props) {
    super(props);
      this.state = {
        productId: (props.route.params && props.route.params.productId ? props.route.params.productId : -1),
        listData: '',
        selectedId: '',
        setSelectedId: '',
        currentPage: 1,
        loadMoreVisible: true,
        loadMoreVisibleAtEnd: false,
        displayArray: []
      }
    };

  initListData = async () => {
    let list = await getProducts(1);
   
    if (list) {
      this.setState({
        displayArray: list,
        loadMoreVisible: (list.length >= 10 ? true : false), 
        currentPage: 2
      });
    }
  };

  setNewData = async (page) => {
    let list = await getProducts(parseInt(page));

    if (list) {
      this.setState({
        displayArray: this.state.displayArray.concat(list),
        loadMoreVisible: (list.length >= 10 ? true : false),
        loadMoreVisibleAtEnd: false,
        currentPage: parseInt(page)+1
      });
    }
  };

  loadMore() {
   this.setNewData(this.state.currentPage);
  }

  displayBtnLoadMore() {
    this.setState({
      loadMoreVisibleAtEnd: true
    });
  }

  async componentDidMount() {
    this.initListData();
  }

   render() {
  //console.log('url', URL );
  //console.log('displayArray', this.state.displayArray);
  //console.log('name', this.state.displayArray.name);
  //console.log('photo', this.state.displayArray.photo);
    return (
      <View style={{flex: 1}}>
        {this.state.displayArray !== null && this.state.displayArray.length > 0 ? (
          <View style={{ flex: 1}}>
            <SafeAreaView>               
              <FlatList
                data={this.state.displayArray}
                extraData={this.selectedId}
                style={{width: '98%'}}
                onEndReached={() => this.displayBtnLoadMore()}
                renderItem={({item, index, separators })=>
                  <View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center'}}>
                    <ListItem
                      style={{width:'100%'}}
                      containerStyle= {{backgroundColor: index % 2 === 0 ? '#fde3a7' : '#FFF'}}
                      bottomDivider
                      onPress={() => this.props.navigation.navigate('ProductDetails', {productId:parseInt(item.id)})}>
                      <ListItem.Content style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                        {item.photo !== null && item.photo > 0 ? (
                          <Image 
                            source={{uri: URL + item.photo._1_.url}}
                            style={{ width: 25, height: 25}}/> 
                        ) : (
                          <Image 
                            source={require('../../../assets/images/logo.png')}
                            style={{ width: 25, height: 25}}
                          />
                        )};
                        <ListItem.Title style={{width: '65%', fontSize: 16}}>{ ( item.name.length > 20 ) ? item.name.substring(0, 20) + ' ...'  :  item.name}</ListItem.Title>
                        <ListItem.Subtitle style={{ color: '#F78400', position: "absolute", bottom: 0, right: 0 }}>{item.cost}{i18n.t("products.money")}</ListItem.Subtitle>
                      </ListItem.Content>
                    </ListItem>
                  </View>
                }
                keyExtractor={(item,index)=>index.toString()}
                style={{width:"100%"}}
              />
              {this.state.loadMoreVisible === true && this.state.loadMoreVisibleAtEnd === true ? (
                  <Button title=" + " onPress={()=>{this.loadMore()}}></Button>
                ) : null
              }
              <View style={styles.container}>
                <Text>{"\n"}</Text>
                <TouchableOpacity
                  style={styles.touchable2}
                  onPress={() => this.props.navigation.goBack()}
                >
                  <View style={styles.container}>
                    <Button
                      color="#F78400"
                      title= 'Back'
                      onPress={() => this.props.navigation.goBack()}>BACK
                    </Button>
                  </View>
                </TouchableOpacity>
              </View>
              <Text>{"\n\n"}</Text>
            </SafeAreaView>
          </View>
        ) : (
          <View style={styles.container}>
            <Text>{"\n\n" + (this.state.displayArray === null ? i18n.t("products.searching") : i18n.t("products.nodata")) + "\n\n\n"}</Text>
            <Button
              color="#F78400"
              title= 'Back'
              onPress={() => this.props.navigation.goBack()}>BACK
            </Button>
          </View>
        )}
      </View>
    );
  };
}

我对如何做到这一点有点迷茫,所以如果你有任何线索可以帮助我,任何线索都会很棒。非常感谢

【问题讨论】:

    标签: javascript react-native conditional-rendering


    【解决方案1】:

    本次测试:

    item.photo !== null &amp;&amp; item.photo &gt; 0

    不会返回您期望的结果。原因是当没有照片时,属性设置为空字符串。所以测试的第一部分应该是:

    item.photo !== ''

    接下来,当有照片时,photo 属性是一个对象。所以第二部分应该是:

    item.photo.constructor === 'Object'

    但是,如果有不止一张照片,那就更复杂了。您的代码表明您只想要第一张照片(无论有多少)。

    因此,如果您按照我的建议进行更改,它应该会按您的预期工作。

    如果我是你,我会完全跳过第一个测试,因为现在第二个测试涵盖了这两种情况,所以没有必要。我建议这样做:

    {item.photo.constructor === 'Object' ? (

    【讨论】:

    • 谢谢你,我理解你的解释,感谢你花时间分解和解释。我正在测试,仍然有这个错误“[未处理的承诺拒绝:错误:文本字符串必须在组件内呈现。]”我不明白,我把条件放在错误的地方吗?
    • 我在这里看不到它,但你的渲染中有纯文本返回某个地方。我建议您删除一点时间,看看您是否可以隔离它在哪里。它可以像非打印空白字符一样简单(您在屏幕上看不到)。但是在这段代码中我什么都看不到。
    • 我认为这是我的第一个条件,{this.state.displayArray !== null && this.state.displayArray.length > 0 ? (.......因为,删除它使它工作正常......它让我有点烦恼,为了安全我把它戴上但是嘿,也许我最终会删除它,这样一切都好......
    • 好吧,终于用这个了:'{item.photo.constructor === 'Object' ? (' 没有用,但单独使用 'item.photo !== '' ' 工作正常。再次感谢您的帮助。我真的很感激
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 2021-03-08
    • 1970-01-01
    • 2021-10-26
    相关资源
    最近更新 更多