简体   繁体   English

React-Native for loop 使用 FlatList 给出错误

[英]React-Native for loop using FlatList is giving error

I am new in programming.我是编程新手。 I would like to render list dynamically.我想动态呈现列表。 The parent component Navbar has state with Food Type category like Mexican, Chinese.父组件 Navbar 的 state 具有墨西哥、中国等食物类型类别。 Each of the FoodTypes have their respective Menu每个 FoodTypes 都有各自的菜单

What I like is to render first FoodType and then its respective Menu in FlatList.我喜欢先渲染 FoodType,然后在 FlatList 中渲染其各自的菜单。 The data is saved in Navbar Component.数据保存在导航栏组件中。 I can render the FoodType using FlatList, but problem is in for loop logic.The for loop is giving me error.我可以使用 FlatList 渲染 FoodType,但问题在于 for 循环逻辑。for 循环给了我错误。 Please see the sandbox:请看沙箱:

https://codesandbox.io/s/hungry-lamarr-p8mq3 https://codesandbox.io/s/hungry-lamarr-p8mq3

The relevant code is below(line 130-154), in Menu Component相关代码如下(第 130-154 行),在菜单组件中

render() {
   
    return (
      <View className="container-fluid">
    
    <Text> Here use Flatlist</Text>
    
    
    for (let i = 0; i < this.props.Objs_Type.length; i++) {
    <FlatList 
    data={this.props.Objs_Type}
    renderItem={({item})=>
    <Text>{item.FoodType[i]}</Text>
    <Text>{item.Menu[i]}</Text>
   }
   keyExtractor={(item,index)=>item.id}
   /> 
  };
 
  
    </View>

    ) 
  }

use nested flat list one vertical and horizontal flatlist to get the ui使用嵌套平面列表一个垂直和水平平面列表来获取用户界面

check below code snack: https://snack.expo.io/@ashwith00/list检查以下代码小吃: https://snack.expo.io/@ashwith00/list

code:代码:

import * as React from 'react';
import { Text, View, StyleSheet, FlatList } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

const data = [
  {
    title: 'Chinese',
    data: [1, 2, 3, 4],
  },
  {
    title: 'Mexican',
    data: [1, 2, 3, 4],
  },
  {
    title: 'Indian',
    data: [1, 2, 3, 4],
  },
  {
    title: 'Indian',
    data: [1, 2, 3, 4],
  },
];
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

export default function App() {
  const renderCategory = ({ item }) => (
    <View style={{ alignSelf: 'stretch', height: 200, marginBottom: 20 }}>
      <Text>{item.title}</Text>
      <FlatList
        keyExtractor={(_, i) => i.toString()}
        data={item.data}
        horizontal
        renderItem={renderBar}
        showsHorizontalScrollIndicator={false}
      />
    </View>
  );

  const renderBar = ({ item }) => (
    <View
      style={{
        height: '100%',
        width: 240,
        backgroundColor: 'red',
        marginRight: 10,
      }}
    />
  );
  return (
    <View style={styles.container}>
      <FlatList
        showsVerticalScrollIndicator={false}
        data={data}
        keyExtractor={(_, i) => i.toString()}
        renderItem={renderCategory}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

You need to change your render() function in this way:您需要以这种方式更改您的render() function:

render() {

    return (
        <View className="container-fluid">

            <Text> Here use Flatlist</Text>

            <FlatList
                data={this.props.Objs_Type}
                renderItem={({ item }) => (
                    <View>
                        <Text>{item.FoodType}</Text>
                        <Text>{item.Menu}</Text>
                    </View>
                )}
                keyExtractor={(item, index) => item.id}
            />

        </View>

    )
}

The error which I saw in the sandbox link you provided is "Unexpected token".我在您提供的沙盒链接中看到的错误是“意外令牌”。 Whenever you get this error, it is most likely due to a syntactic mistake.每当您收到此错误时,很可能是由于语法错误。 In your case, it was missing curly braces around your for-loop.在您的情况下,您的 for 循环周围缺少花括号。 Remember whenever you embed any JavaScript code into a JSX block, make sure you encapsulate the JavaScript codes within curly braces.请记住,每当您将任何 JavaScript 代码嵌入到 JSX 块中时,请确保将 JavaScript 代码封装在花括号中。

return (
   <jsx-code>
     {
        some-js-logic like if-else, etc.
     }
   </jsx-code>
)

Now in your case, even if you add a pair of braces, it won't work, because the for loop in JSX won't work that way.现在在你的情况下,即使你添加一对大括号,它也不会工作,因为 JSX 中的 for 循环不会那样工作。 More on this in the first link which I provided at the end.我在最后提供的第一个链接中对此进行了更多介绍。

And to solve your problem, you don't have to use a for-loop at all.为了解决您的问题,您根本不必使用 for 循环。 The FlatList component accepts the array in its data param. FlatList组件在其data参数中接受该数组。 So you don't have to loop through the array.所以你不必遍历数组。 All you got to do is use the items of this array to render your own UI.您所要做的就是使用此数组的项目来呈现您自己的 UI。 Here's a sample which is the simplest representation of your code snippet.这是一个示例,它是您的代码片段的最简单表示。

  render() {
    return (
      <View className="container-fluid">
        <Text> Here use Flatlist </Text>
        {
          this.generateFlatList(this.props.Objs_Type)
        }
      </View>
    );
  }

  generateFlatList(objsTypes) {
    console.log(objsTypes);
    return (
      <FlatList
        data={objsTypes}
        renderItem={({item}) => <Text>{item.FoodType}</Text>}
        keyExtractor={(item) => item.id}
      />
    );
  }

Here are some links which might help you learn more about using for-loop in React JSX and FlatList component:这里有一些链接可以帮助你了解更多关于在 React JSX 和 FlatList 组件中使用 for-loop 的信息:

Thanks all for the valuable comments.感谢大家的宝贵意见。 Helped me learned alot.帮助我学到了很多。 If someone is interested, below is the corrected code如果有人感兴趣,下面是更正的代码

  <View className="container-fluid">
        <Text> Here use Flatlist</Text>

        <FlatList
          data={this.props.Objs_Type}
          renderItem={({ item }) => (
            <React.Fragment>
              <Text>{item.FoodType}</Text>
              {item.Menu.map(e => (
                <Text>{e}</Text>
              ))}
            </React.Fragment>
          )}
          keyExtractor={item => item.id}
        />
      </View>

renderItem if you put two tags like two Texts, it will iterate it automatially. renderItem 如果你放两个标签,比如两个文本,它会自动迭代它。 So in my case, i had two items in Food_Type and 3 Menu items in each of Food_Type.因此,就我而言,我在 Food_Type 中有两个项目,每个 Food_Type 中有 3 个菜单项。 if you just use two Text each for Food_Type and Menu, it will first print Chinese, then the array ofMenu of Chinese.如果只对 Food_Type 和 Menu 分别使用两个 Text,它将首先打印 Chinese,然后是 Chinese 的数组 ofMenu。 To display Menu vertically i had to use map.要垂直显示菜单,我必须使用 map。

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

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