【问题标题】:Flatlist numColumns issuesFlatlist numColumns 问题
【发布时间】:2020-05-08 18:39:14
【问题描述】:

我正在尝试根据用户选择的内容打印一组图像并将它们打印在 2 列上,但我在这样做时遇到了问题

import React, { Component } from 'react';
import {View, FlatList} from 'react-native';
import {f, auth, database} from '../../config/firebase';
import {SearchBar} from "react-native-elements";
import {ArtObjectCard} from "../components/ArtObjectCard";





export default class ExhibitionDetailScreen extends Component{

    static navigationOptions = {
        headerShown: false,
    };



  constructor(props)
  {
    super(props);
    this.state = {
        exhibit: props.navigation.state.params.exhibit,
        objectIds: [],
        objects: []
  };

  }

  getObject = (objId) => {

      const ref = database.ref('object').child(objId);


      ref.once('value').then((snapshot) => {
          let object =  snapshot.val();

          object["id"] = objId;

          this.state.objects.push(object);

      });
  }


  getData = () => {

      database.ref(`exhibition_object/${this.state.exhibit.id}`).once('value')
          .then((snapshot) => {
              this.setState({
                  objectIds: Object.keys(snapshot.val())

              })

              for( let i = 0;i < this.state.objectIds.length;i++ )
              {
                  // Create a new array based on current state:
                  let arr = [...this.state.objects];

                  // Add item to it
                  arr.push(this.getObject(this.state.objectIds[i]));

                  // Set state
                  this.setState({ objects: arr });
              }
          });



  }


    componentDidMount () {

        this.getData()


    }

    keyExtractor = (item, index) => {

        return index.toString();
    }



    renderItem = ({item, index}) => {


        if (!item) {
            return null
        }

        return (
            <View>

                <ArtObjectCard
                    title={item.title}

                    image={{uri: item.image}}

                    onClickButton={()=>{this._onPressItem(item)}}
                />

            </View>
        );
    }




    render(){
        const { search } = this.state;
        return (

            <View style={{flex: 1}}>

                <SearchBar
                    placeholder="Type something here...."
                    onChangeText={this.updateSearch}
                    value={search}
                />

                <FlatList
                    data={this.state.objects}
                    renderItem={this.renderItem}
                    keyExtractor={this.keyExtractor}
                    numColumns={2}

                />
            </View>
        );
    }
}


我正在使用 firebase 来获取图像。 当我有 3 个项目的数组时,就会出现这个问题

当我有 2 个元素的 aray 时没有问题

我有这个问题是因为数据没有时间加载,还是我该如何解决这个问题?

编辑 1: 我试过了,但它仍然不适合我

  renderItem = ({item, index}) => {


        return (
            <View>

                <ArtObjectCard
                    title={item?item.title:""}

                    image={{uri:item.image}}

                    onClickButton={()=>{this._onPressItem(item)}}
                />

            </View>
        );
    }

ArtObjectCard 类

import React, { Component } from "react";
import {
    Text,
    View,
    Image,
    Dimensions,
    Platform,
    ProgressViewIOS,
    ProgressBarAndroid,
} from "react-native";
let screenWidth = Dimensions.get("window").width;

export class ArtObjectCard extends Component<Props> {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <View
                style={{
                    height: 200,
                    margin: 10,


                }}
            >
                <View

                >
                    <Image
                        borderRadius={10}
                        source={this.props.image}
                        style={{
                            width: this.props.width ? this.props.width : screenWidth/2  - 20,
                            height: this.props.height ? this.props.height : 200,
                            resizeMode: "cover"
                        }}
                    />

                </View>
            </View>
        );
    }
}

编辑2:

如果我替换this.setState({ objects: arr });这一行

this.setState({  arr });

3 个对象将被正确打印,但当有 2 个对象时出现空白屏幕

【问题讨论】:

    标签: javascript reactjs firebase react-native react-native-flatlist


    【解决方案1】:

    问题是你是这样检查的

    if (!item) {
            return null
        }
    

    那么如果你的数据集是这样的

    objects = [{title:"A",Image:""},{},{title:"A",Image:""},{title:"A",Image:""}]
    

    它将在数组的第二个元素处返回 null,因为 !item 条件以这种方式为真。 所以你的函数应该是这样的:

    renderItem = ({item, index}) => {
    
    
        return (
            <View>
    
                <ArtObjectCard
                    title={item?item.title:""}
    
                    image={{uri:item? item.image:"Some default url"}}
    
                    onClickButton={()=>{this._onPressItem(item)}}
                />
    
            </View>
        );
    }
    

    【讨论】:

    • 你好,我试过了,但不幸的是它仍然像第一张图片一样,带有警告并且顺序不正确
    • 如果我删除 numColumns={2} 它会打印所有 3 个且没有错误
    • 你能分享一下物品里有什么吗?只需 conosle 并共享其中的数据
    • 如果 item 中有 id 然后替换 item.id} 中的 prop
    • 我也试过了,但没用,数组中有3个这样的对象:Object { "artist": "Edward Hopper", "artistInfo": "American, 1882 - 1967", "classification": "Painting", "date": 1939, "dimensions": "overall: 91.92 × 127.16 cm (36 3/16 × 50 1/16 in.) framed: 127.3 × 152.4 cm (50 1/8 × 60 in.)", "id": "yXz03", "image": "https://images.nga.gov/?service=asset&amp;action=show_preview&amp;asset=148908", "medium": "oil on canvas", "title": "Ground Swell", }
    【解决方案2】:

    查看 return null 它的行为与 wating 相同 如果我删除 return null 效果很好

    【讨论】:

    • 它对我不起作用,我不知道我做错了什么:(
    • @GherghinaAndrei 可以分享 ArtObjectCard 的代码吗?
    猜你喜欢
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2022-08-08
    • 1970-01-01
    • 2019-12-20
    相关资源
    最近更新 更多