Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 根据数据库数据的存在添加条件_Javascript_React Native_Conditional Rendering - Fatal编程技术网

Javascript 根据数据库数据的存在添加条件

Javascript 根据数据库数据的存在添加条件,javascript,react-native,conditional-rendering,Javascript,React Native,Conditional Rendering,我有一个要添加图像的列表。 基本上我的代码运行良好,我使用的API数据库不幸发生了变化。。。我数据库中的一些产品没有图像,所以当我调用有问题的线路时,它会给我一个错误。。。 因此,我想创建一个条件:如果数据库中有相关产品的图像,我想显示它 图像源={{uri:URL+item.photo.1.URL} 否则,我希望它是一个预设的标志。 0 ? ( ) : ( )}; {(item.name.length>20)?item.name.substring(0,20)+'…':item.name} {

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

图像源={{uri:URL+item.photo.1.URL}

否则,我希望它是一个预设的标志。 0 ? ( ) : ( )}; {(item.name.length>20)?item.name.substring(0,20)+'…':item.name} {item.cost}{i18n.t(“products.money”)} 但我有两个错误:

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>
    );
  };
}
导出默认类产品扩展组件{
建造师(道具){
超级(道具);
此.state={
productId:(props.route.params&&props.route.params.productId?props.route.params.productId:-1),
listData:“”,
选择ID:“”,
setSelectedId:“”,
当前页面:1,
是的,
LoadMoreVisibleAndend:false,
displayArray:[]
}
};
initListData=async()=>{
let list=等待获取产品(1);
如果(列表){
这是我的国家({
displayArray:list,
loadMoreVisible:(list.length>=10?真:假),
当前页:2
});
}
};
setNewData=async(第页)=>{
let list=wait-getProducts(parseInt(第页));
如果(列表){
这是我的国家({
displayArray:this.state.displayArray.concat(列表),
loadMoreVisible:(list.length>=10?真:假),
LoadMoreVisibleAndend:false,
当前页面:parseInt(第+1页)
});
}
};
loadMore(){
this.setNewData(this.state.currentPage);
}
displayBtnLoadMore(){
这是我的国家({
LoadMoreVisibleAndend:正确
});
}
异步组件didmount(){
this.initListData();
}
render(){
//log('url',url);
//log('displayArray',this.state.displayArray);
//log('name',this.state.displayArray.name);
//log('photo',this.state.displayArray.photo);
返回(
{this.state.displayArray!==null&&this.state.displayArray.length>0(
this.displayBtnLoadMore()}
renderItem={({项,索引,分隔符})=>
this.props.navigation.navigate('ProductDetails',{productId:parseInt(item.id)}>
{item.photo!==null&&item.photo>0(
) : (
)};
{(item.name.length>20)?item.name.substring(0,20)+'…':item.name}
{item.cost}{i18n.t(“products.money”)}
}
keyExtractor={(项,索引)=>index.toString()}
样式={{width:“100%”}
/>
{this.state.loadMoreVisibleAndend==true&&this.state.loadMoreVisibleAndend==true(
{this.loadMore()}}>
):null
}
{“\n”}
this.props.navigation.goBack()}
>
this.props.navigation.goBack()}>BACK
{“\n\n”}
) : (
{“\n\n”+(this.state.displayArray==null?i18n.t(“products.search”):i18n.t(“products.nodata”)+“\n\n\n”}
this.props.navigation.goBack()}>BACK
)}
);
};
}
我对怎么做有点迷茫,所以如果你有任何线索可以帮助我,任何线索都会很好。非常感谢这次测试:

item.photo!==null&&item.photo>0

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

item.photo!==''

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

item.photo.constructor=='Object'

但是,如果有一张以上的照片,情况会更加复杂。你的代码表明你只想要第一张照片(不管有多少张)

所以,如果你做了我建议的更改,它应该会像你所期望的那样工作

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


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

谢谢您,我理解您的解释,感谢您花时间进行分解和解释。我正在测试,但仍然存在以下错误“[未处理的承诺拒绝:错误:必须在组件内呈现文本字符串。]”我不明白,是我把条件放错地方了吗?我在这里看不到,但你的渲染中有纯文本返回到某个地方。我建议你删除一点时间,看看是否可以隔离它在哪里。它可以是像非打印空白字符这样简单的东西(你在屏幕上看不到).但是在这段代码中我看不到任何东西。我想这是我的第一个条件,{this.state.displayArray!==null&&this.state.displayArray.length>0?(……因为,
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>
    );
  };
}