简体   繁体   English

反应原生平面列表不渲染项目

[英]React native flat list not rendering items

I hope you're doing okay我希望你一切都好

I'm experiencing something weird with my react-native project, The FlatList items in some of the pages aren't displayed, even though I can see them when I console.log(json.items).我的 react-native 项目遇到了一些奇怪的事情,某些页面中的 FlatList 项目没有显示,即使我在 console.log(json.items) 时可以看到它们。

Earlier today, everything worked fine.今天早些时候,一切正常。 all the pages displayed their lists as they should on my device.所有页面都在我的设备上显示了它们的列表。 then I started working on a new search page on snack & I added status bar, I tested and it worked on snack before adding the new code and creating the new files in my app.然后我开始在零食上创建一个新的搜索页面,并添加了状态栏,我在添加新代码并在我的应用程序中创建新文件之前测试了它在零食上的工作。

The issue I'm having now is, the list on the first page is displayed, subsequent pages after that do not show list items.我现在遇到的问题是,显示第一页上的列表,之后的后续页面不显示列表项。 including the new search page that works on snack包括适用于零食的新搜索页面

I'll go ahead and post my code now, the first set is for the page whose listitems are displayed correctly:我会提前 go 并现在发布我的代码,第一组是正确显示列表项的页面:

App.js应用程序.js

class ProfileActivity extends Component
{

  // Setting up profile activity title.
   static navigationOptions = ({ navigation }) =>
   {
     return {
      title: 'Home',
      headerStyle : {
        backgroundColor: '#00b47a',
        elevation: 0
      },
      headerTitleStyle: {
        color: 'white'
      },
      cardStyle: { backgroundColor: '#fff' },
      headerLeft: null,
      headerRight: (
        <View style={{ alignSelf: 'center', alignItems: 'center', display: 'flex', flexDirection: 'row', justifyContent: 'space-evenly'}}>
        <Icon containerStyle={{ paddingRight: 10 }}
        color='#fff' onPress={()=> navigation.getParam('openBottomSheet')()}
        name="menu" />
        <Icon containerStyle={{ paddingRight: 15 }}
        color='#fff' onPress={()=> navigation.getParam('openSearchPage')()}
        name="search" /></View>
      )
     }
   };

   constructor () {
    super()
    this.state = { toggled: false }
  }

  componentDidMount() {
    this.props.navigation.setParams({ openBottomSheet: this.onOpenBottomSheet });
    this.props.navigation.setParams({ openSearchPage: this.onOpenSearchPage });
  }

  onOpenBottomSheet = ()  => {
     this.Standard.open();
  }
  onOpenSearchPage = ()  => {
    this.props.navigation.navigate('sixth');
 }

  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'}}>
        
      <StatusBar
      animated={true}
      backgroundColor="#00b47a"
      barStyle={'light-content'}
      showHideTransition={'slide'}
      hidden={false} />
         <MarketList navigation={this.props.navigation} />
         <RBSheet
           ref={ref => {
             this.Standard = ref;
           }}        
         >
...
         </RBSheet>
         </View>
    );
  }
}            
 

Market.js Market.js

export default class MarketList extends React.Component {
  constructor(props) {
 
    super(props)
 
    this.state = {
      items: '',
    };
    this.animateList = new Animated.Value(0);
}

componentDidMount() {
  Animated.timing(this.animateList, {
    toValue: 1,
    duration: 500,
  }).start();
}
  render() {
    const rowStyles = [
        styles.itemList,
        { opacity: this.animateList },
        {
          transform: [
            { scale: this.animateList },
          ],
        },
      ];

      
    fetch('https://mvmarket.xyz/nativeuserapp/home.php')
    .then((response) => response.json())
    .then((json) => {
      this.setState({
        items: json.items,
      })
    })
    .catch((error) => {
      console.error(error);
    });
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.items}
          renderItem={({item}) => <TouchableOpacity onPress={()=>this.props.navigation.navigate("fourth",{market:item.name})}><Animated.View style={rowStyles}><View style={styles.item}><Text style={styles.market}>{item.name}</Text><Text style={styles.location}>{item.Location}</Text></View><View style={styles.go}><Icon name="arrow-right" color="#00b47a" /></View></Animated.View></TouchableOpacity>}
        />
      </View>
    );
  }
}

This next set is for one of the pages that don't show list items下一组用于不显示列表项的页面之一

App.js应用程序.js

class ProductsActivity extends Component {
  static navigationOptions =
  {
     title: 'Products',
     headerStyle : {
       backgroundColor: '#00b47a',
       elevation: 0
     },
    cardStyle: { backgroundColor: '#fff' },
     headerTitleStyle: {
       color: 'white'
     },
  };

  render() {

    return(
      <View>
      <StatusBar
      animated={true}
      backgroundColor="#00b47a"
      barStyle={'light-content'}
      showHideTransition={'slide'}
      hidden={false} />
      <ProductsList navigation={this.props.navigation} />
      </View>
    );
  }
}

Products.js Products.js

export default class ProductsList extends React.Component {
  constructor(props) {
 
    super(props)
 
    this.state = {
      items: '',
    };
  }
  
  render() {
    fetch('https://mvmarket.xyz/nativeuserapp/products.php')
    .then((response) => response.json())
    .then((json) => {
      this.setState({
        items: json.items,
      })
    }).catch((error) => {
      console.error(error);
      console.log(error);
    });
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.items}
          renderItem={({item}) => <TouchableOpacity onPress={()=>this.props.navigation.navigate("fifth",{market: this.props.navigation.state.params.market, type:item.type})} style={styles.itemList}><View style={styles.item}><Text style={styles.market}>{item.type}</Text></View><View style={styles.go}><Icon name="arrow-right" color="#00b47a" /></View></TouchableOpacity>}
        />
      </View>
    );
  }
}

I'm leaving the URL there so you can confirm yourself that the data is actually fetched.我将 URL 留在那里,这样您就可以确认自己确实获取了数据。 Its driving me crazy, been on it for like 4 hrs.它让我发疯,坚持了 4 个小时。

Thank you谢谢

I think you don't really understand lifecycle methods of a React Component.我认为您并不真正了解 React 组件的生命周期方法。 It's important to understand those concepts before jumping into code.在开始编写代码之前理解这些概念很重要。 You can check here你可以在这里查看

When you put your fetch call in render , and on then you do a setState() you are making this infinitely.当您将 fetch 调用放入render时,然后您执行setState()您正在无限地进行此操作。 This happens because you are always providing new values to items .发生这种情况是因为您总是为items提供新值。

The ideal is to have a model layer to handle those type of calls, but this is an architecture thing, to be less complex, you can use Container/Presentation pattern.理想的情况是有一个 model 层来处理这些类型的调用,但这是一个架构问题,为了不那么复杂,您可以使用容器/演示模式。

In the Container/Presentation pattern, you have a ContainerComponent which is responsible to do requests, handle callbacks, and provide data to the Presentation component, which would be responsible to just render things.在 Container/Presentation 模式中,您有一个 ContainerComponent 负责执行请求、处理回调并向 Presentation 组件提供数据,而 Presentation 组件将负责渲染事物。

If you don't want to use this pattern, at least put this fetch call in componentDidMount method.如果你不想使用这种模式,至少把这个 fetch 调用放在componentDidMount方法中。

Thank you all for your suggestions, duly noted and appreciated.谢谢大家的建议,适当的注意和赞赏。

@Witalo-Benicio @Andris-laduzans @Drew-reese @Witalo-Benicio @Andris-laduzans @Drew-reese

I've fixed it, by changing我已经修复它,通过改变

class SearchMarketActivity extends Component {
  static navigationOptions = {
    headerShown: false, 
    cardStyle: {
      backgroundColor: 'white'
    }
  }

  render() {
    return(
       <View>
        <StatusBar
        animated={true}
        backgroundColor="#585858"
        barStyle={'light-content'}
        showHideTransition={'slide'}
        hidden={false} />

        <SearchMarket navigation={this.props.navigation} />
</View>
    )
  }
}

to

class SearchMarketActivity extends Component {
  static navigationOptions = {
    headerShown: false, 
    cardStyle: {
      backgroundColor: 'white'
    }
  }

  render() {
    return(
        <SearchMarket navigation={this.props.navigation} />
    )
  }
}

After, I added the StatusBar to the <SearchMarket /> component being imported之后,我将StatusBar添加到正在导入的<SearchMarket />组件中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM