未定义不是函数(靠近'...item.map...')-React Native 搜索栏

时间:2021-03-19 16:12:55

标签: javascript arrays reactjs react-native

我遇到此错误“未定义不是函数(靠近'...item.map...')。 我有一个名为 recipes 的数据,我想要做的是过滤数据并在搜索时显示它。当我在搜索框中输入文本时发生错误。 我试图修复它一段时间,但我无法修复它。请帮忙

import React, { Component } from "react";
import {
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  Button,
  TouchableOpacity,
} from "react-native";
import { FlatList, ImageBackground } from "react-native";
import { SearchBar, Card } from "react-native-elements";
import { RECIPES } from "../shared/recipe";
import Header from "./Header";
import * as Font from "expo-font";

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      recipes: RECIPES,
      fontsLoaded: false,
      search: [],
    };
  }

  static navigationOptions = {
    title: "Home",
  };

 
  updateSearch = (recipe) => {
    this.setState({
     
      search: this.state.recipes.filter((rec) =>
        rec.name.toLowerCase().includes(recipe.toLowerCase())
      ),
    });
  };
  render() {
    const { navigate } = this.props.navigation;

    const renderRecipeItem = ({ item }) => {
      if (item) {
        item.map((recipe) =>
          recipe.recipes.map((rec) => {
            return (
              <View
                key={recipe.title + recipe.author + recipe.prepTime}
                style={{
                  borderRadius: 8,
                  margin: 10,
                  padding: 20,

                  justifyContent: "center",
                  alignItems: "center",
                  shadowOffset: {
                    width: 1,
                    height: 2,
                  },
                  shadowColor: "grey",
                  shadowOpacity: 0.8,
                  elevation: 2,
                }}
              >
                <View
                  style={{
                    position: "relative",
                    borderTopStartRadius: 8,
                    borderTopEndRadius: 8,
                    overflow: "hidden",
                    justifyContent: "center",
                    alignItems: "center",
                  }}
                >
                  <Image
                    style={{
                      minWidth: "100%",
                      height: 200,
                    }}
                    source={{ uri: rec.image }}
                  />
                  <View style={styles.overlay}></View>
                  <Text
                    style={{
                      position: "absolute",
                      top: "40%",
                      color: "rgb(255,250,160)",

                      fontFamily: "RobotoMono-Light",

                      fontSize: 28,
                    }}
                  >
                    {rec.country}
                  </Text>
                </View>
                <TouchableOpacity
                  style={{
                    alignItems: "center",
                    backgroundColor: "#BF360C",
                    padding: 10,
                    marginTop: 20,
                    borderRadius: 8,
                    opacity: 0.7,
                    width: "100%",
                  }}
                  onPress={() => navigate("FoodInfo", { recipeId: item.id })}
                >
                  <Text style={{ fontSize: 24 }}>RECIPES</Text>
                </TouchableOpacity>
              </View>
            );
          })
        );
      }
      return <View />;
    };

    return (
      <View>
        <ScrollView style={{}}>
          <Header />
          <SearchBar
            round
            lightTheme
            style={{ borderRadius: 5 }}
            placeholder="Search a recipe..."
            onChangeText={(recipe) => this.updateSearch(recipe)}
          />

          <FlatList
            data={this.state.search}
            renderItem={renderRecipeItem}
            keyExtractor={(item) => item.id.toString()}
          />
        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  overlay: {
    position: "absolute",
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    backgroundColor: "red",
    opacity: 0.3,
  },
});

export default Home;

这是食谱数据-

export const RECIPES = [
  {
    id: 0,
    name: "thai",
    country: "Thai Cuisine",
    recipes: [
      {
        recipeTitle: "Pad Thai",
        author: "Helen Ma",
        rating: 5,
        prep: "10 mins",
        cook: "55 mins",
        total: "1 hr 5 mins",
        image:
          "https://images.unsplash.com/photo-1568146244603-ea84f076d043?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NDl8fHRoYWklMjBmb29kfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
        video: "https://www.youtube.com/watch?v=oD1DlijLo_I",
        description: "A very delicious  Thai food that you will enjoy",
        date: new Date().toDateString(),
      },
      {
        recipeTitle: "Sushi",
        author: "Laura Chan",
        rating: 5,
        prep: "10 mins",
        cook: "55 mins",
        total: "1 hr 5 mins",
        image:
          "https://images.unsplash.com/photo-1568146244603-ea84f076d043?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NDl8fHRoYWklMjBmb29kfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
        video: "https://www.youtube.com/watch?v=oD1DlijLo_I",
        description: "A very delicious  Thai food that you will enjoy",
        date: new Date().toDateString(),
      },
    ],
  },

  {
    id: 1,
    name: "taiwanese ",
    country: "Taiwanese Cuisine",
    recipes: [
      {
        recipeTitle: "Noodles",
        author: "Audrey Wang",
        rating: 5,
        prep: "10 mins",
        cook: "55 mins",
        total: "1 hr 5 mins",
        image:
          "https://images.unsplash.com/photo-1613276016849-469ca6b326bd?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OXx8Zm9vZCUyMHRoYWl8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
        video: "https://www.youtube.com/watch?v=oD1DlijLo_I",
        description: "A very delicious Taiwanese food that you will enjoy",
        date: new Date().toDateString(),
      },
      {
        recipeTitle: "Beef Noodle Soup",
        author: "Jesse Lin",
        rating: 5,
        prep: "10 mins",
        cook: "55 mins",
        total: "1 hr 5 mins",
        image:
          "https://images.unsplash.com/photo-1613276016849-469ca6b326bd?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OXx8Zm9vZCUyMHRoYWl8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
        video: "https://www.youtube.com/watch?v=oD1DlijLo_I",
        description: "A very delicious Taiwanese food that you will enjoy",
        date: new Date().toDateString(),
      },
    ],
  },
  {
    id: 2,
    name: "american",
    country: "American Cuisine",
    recipes: [
      {
        recipeTitle: "Burger",
        author: "James Burger",
        rating: 5,
        prep: "10 mins",
        cook: "55 mins",
        total: "1 hr 5 mins",
        image:
          "https://images.unsplash.com/photo-1602030638412-bb8dcc0bc8b0?ixid=MXwxMjA3fDB8MHxzZWFyY2h8M3x8YW1lcmljYW4lMjBmb29kfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
        video: "https://www.youtube.com/watch?v=oD1DlijLo_I",
        description: "A very delicious American food that you will enjoy",
        date: new Date().toDateString(),
      },
      {
        recipeTitle: "Stake",
        author: "James Burger",
        rating: 5,
        prep: "10 mins",
        cook: "55 mins",
        total: "1 hr 5 mins",
        image:
          "https://images.unsplash.com/photo-1602030638412-bb8dcc0bc8b0?ixid=MXwxMjA3fDB8MHxzZWFyY2h8M3x8YW1lcmljYW4lMjBmb29kfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
        video: "https://www.youtube.com/watch?v=oD1DlijLo_I",
        description: "A very delicious American food that you will enjoy",
        date: new Date().toDateString(),
      },
    ],
  },

  {
    id: 3,
    name: "ethiopian",
    country: "Ethiopian Cuisine",
    recipes: [
      {
        recipeTitle: "Misir Wat (Ethiopian Spiced Red Lentils)",
        country: "Ethiopian Cuisine",
        author: "Sara Thomas",
        rating: 5,
        prep: "10 mins",
        cook: "55 mins",
        total: "1 hr 5 mins",

        image:
          "https://food.fnr.sndimg.com/content/dam/images/food/fullset/2016/9/7/0/DV2507H_Misir-Wot-Spicy-Red-Lentils_s4x3.jpg.rend.hgtvcom.826.620.suffix/1473350482641.jpeg",
        video: "https://www.youtube.com/watch?v=oD1DlijLo_I",
        description: "A very delicious Ethiopian food that you will enjoy",
        date: new Date().toDateString(),
      },
      {
        recipeTitle: "Doro Wot",
        author: "Girum Elias",
        rating: 5,
        prep: "10 mins",
        cook: "55 mins",
        total: "1 hr 5 mins",
        image:
          "https://images.unsplash.com/photo-1602030638412-bb8dcc0bc8b0?ixid=MXwxMjA3fDB8MHxzZWFyY2h8M3x8YW1lcmljYW4lMjBmb29kfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
        video: "https://www.youtube.com/watch?v=oD1DlijLo_I",
        description: "A very delicious American food that you will enjoy",
        date: new Date().toDateString(),
      },
    ],
  },
  {
    id: 4,
    name: "Indian",
    country: "Indian Cuisine",
    recipe: [
      {
        recipeTitle: "Chicken Tikka Masala",
        country: "Indian Cuisine",
        author: "Sunita Khan",
        rating: 5,
        prep: "10 mins",
        cook: "55 mins",
        total: "1 hr 5 mins",
        image:
          "https://images.unsplash.com/photo-1542367592-8849eb950fd8?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTB8fGluZGlhbiUyMGZvb2R8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
        video: "https://www.youtube.com/watch?v=oD1DlijLo_I",
        description: "Authentic Indian recipes",
        date: new Date().toDateString(),
      },
      {
        recipeTitle: "Tandoori Chicken",
        country: "Indian Cuisine",
        author: "Sunita Khan",
        rating: 5,
        prep: "10 mins",
        cook: "55 mins",
        total: "1 hr5 mins",
        image:
          "https://images.unsplash.com/photo-1542367592-8849eb950fd8?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTB8fGluZGlhbiUyMGZvb2R8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
        video: "https://www.youtube.com/watch?v=oD1DlijLo_I",
        description: "Authentic Indian recipes",
        date: new Date().toDateString(),
      },
    ],
  },
];

1 个答案:

答案 0 :(得分:0)

我对 React Native 不熟悉,但从 documentation 看来,renderItem 需要传递一个呈现每个单独项目的组件。

此类项目的一个示例是:

{
  id: 0,
  name: "thai",
  country: "Thai Cuisine",
  recipes: [ ... ],
}

意味着 item.map 将导致 undefined 因为 item 不是数组,而是您的“类别”。您必须导航到 recipes 属性,该属性返回一个您可以调用 map 的数组。例如。 item.recipes.map(...)

您还应该删除嵌套的 map 调用 recipe.recipes.map

其他问题主要是命名问题。

  1. recipe.title 不存在。有属性 recipeTitle,但没有 title
  2. recipe.prepTime 不存在。有属性 prep,但没有 prepTime
  3. rec.image 应该是 recipe.image
  4. rec.country 不存在。并且仅适用于“类别”(item)。

style 属性与答案相关,因此我在下面的示例中省略了它们以使事情更容易理解。

const renderRecipeItem = ({ item }) => (
  item.recipes.map((recipe) => (
    <View
      key={recipe.recipeTitle + recipe.author + recipe.prep}
      style={{...}}
    >
      <View style={{...}}>
        <Image style={{...}} source={{ uri: recipe.image }} />
        <View style={styles.overlay}></View>
        <Text style={{...}}>
          {item.country}
        </Text>
      </View>
      <TouchableOpacity
        style={{...}}
        onPress={() => navigate("FoodInfo", { recipeId: item.id })}
      >
        <Text style={{ fontSize: 24 }}>RECIPES</Text>
      </TouchableOpacity>
    </View>
  ))
);

// ...

<FlatList
  data={this.state.search}
  renderItem={renderRecipeItem}
  keyExtractor={(item) => item.id.toString()}
/>