【问题标题】:issues with fetching Json in react在反应中获取 Json 的问题
【发布时间】:2020-11-15 20:42:19
【问题描述】:

我很抱歉,因为这可能是非常基本的,或者我做了一些完全错误的事情。我是 React 的新手,并且一般都在编码,我正在尝试制作一个 React 应用程序来显示我在卡片上使用的食谱。反过来,卡片应该是可搜索的和动态的,如果它们不匹配就会消失等等。

这是我的 app.js 文件,它在运行时只会显示我的自定义“正在加载”屏幕而没有数据。我在哪里搞砸了?

import React, {Component} from 'react';
import CardList from './CardList';
import SearchBox from './SearchBox';
import Scroll from "./Scroll";
import "./App.css"



class App extends Component {
    constructor() {
        super()
        this.state = {
            recipes: [],
            searchfield: "",
        }
    }

    componentDidMount() {
        fetch("./recipedata.json")
        .then(response => { return response.json();})
        .then(recipedata => {this.setState({recipes: recipedata})});
    }

    onSearchChange= (event) =>{
    this.setState({searchfield: event.target.value})
    
    }

    render() {
        const filteredRecipe = this.state.recipes.filter(recipes =>{
            return recipes.name.toLowerCase().includes(this.state.searchfield.toLowerCase());
        })
        if (this.state.recipes.length === 0) {
            return <h1 class="f1 tc">Loading</h1>
        } else {
        return(
            <div className="tc">
            <h1 className="f1">Recipes</h1>
            <SearchBox searchChange={this.onSearchChange} />
            <Scroll>
            <CardList recipe={filteredRecipe}/>
            </Scroll>
            </div>
        )
         }

    }
        
}

export default App

提前致谢

编辑:我被要求发布 recipedata.json 的内容:

    [
    {
        "id" : 1,
        "name" : "Carrot cake",
        "type" : "sweet",
        "author" : "Grandma",
        "link" : "recipes/carrotcake.html"
    },
    {
        "id" : 2,
        "name" : "Spicy chicken pitta filling",
        "type" : "savoury",
        "author" : "Grandma",
        "link" : "recipes/chickenpitta.html"
    },
    {
        "id" : 3,
        "name" : "Mushroom ham and chicken crusty puff pies",
        "type" : "savoury",
        "author" : "Grandma",
        "link" : "recipes/crustypuff.html"
    },
    {
        "id" : 4,
        "name" : "Sweet potato pumpkin seed rolls",
        "type" : "savoury",
        "author" : "Grandma",
        "link" : "recipes/sweetpotrolls.html"
    },
    {
        "id": 5,
        "name": "Wild mushroom wafer",
        "type": "savoury",
        "author" : "Grandma",
        "link": "recipes/mushroomwafer.html"
    },
    {
        "id": 6,
        "name": "Piri Piri chicken sauce",
        "type": "savoury",
        "author": "Grandma",
        "link": "recipes/piriRecipe.html"
    },
    {
        "id": 7,
        "name": "Chicken Liver Pate'",
        "type": "savoury",
        "author": "Grandma",
        "link": "recipes/pate.html"
    },
    {
        "id": 8,
        "name": "Creamy mushroom pasta",
        "type": "savoury",
        "author": "Grandma",
        "link": "recipes/mushroompasta.html"
    },
    {
        "id": 9,
        "name": "Cheesey garlic bread",
        "type": "savoury",
        "author": "Grandma",
        "link": "recipes/gbread.html"
    },
    {
        "id": 10,
        "name": "Mini quiches",
        "type": "savoury",
        "author": "Grandma",
        "link": "recipes/miniquiche.html"
    },
    {
        "id": 11,
        "name": "Sticky lemon ginger cake",
        "type": "sweet",
        "author": "Grandma",
        "link": "recipes/stickyrecipe.html"
    },
    {
        "id": 12,
        "name": "Sticky toffee pudding",
        "type": "sweet",
        "author": "Grandma",
        "link": "recipes/stickytoffee.html"
    },
    {
        "id": 12,
        "name": "Iced cream buns",
        "type": "sweet",
        "author": "Grandma",
        "link": "recipes/icedcreambuns.html"
    },
    {
        "id": 13,
        "name": "Pineapple Cake",
        "type": "sweet",
        "author": "Grandma",
        "link": "recipes/pineapplecake.html"
    }
]

编辑 2:

感谢大家的帮助,我现在已经修复了 app.js 文件,并且正在返回 Json。我现在在 CardList.js 组件中遇到了这个错误:

TypeError: Cannot read property 'map' of undefined
CardList
C:/Users/mattj/OneDrive/Desktop/coding/gmcb-react-app/src/CardList.js:5
  2 | import Card from './Card.js';
  3 | 
  4 | const CardList = ({recipes}) => {
> 5 |    return <div>
  6 |       {recipes.map((recipedata, i) => {
  7 |         return( 
  8 |         <Card 

代码:

    import React from 'react';
import Card from './Card.js';

const CardList = ({recipes}) => {
   return <div>
      {recipes.map((recipedata, i) => {
        return( 
        <Card 
        key={i} 
        id={recipes[i].id} 
        name={recipes[i].name} /> 
        )
    })}
    </div>
}

导出默认卡片列表

我在这里搞砸了什么?

【问题讨论】:

  • 请发./recipedata.json的内容。
  • 你能不能在渲染函数中做一个console.log(this.state.recipes) 并检查recipedata 是否被正确获取。
  • this.state.recipes.length 应该是 &gt; 0 代码才能正确呈现配方。这就是代码中的 else 子句。
  • 这是添加控制台日志后的控制台内容-[]length: 0__proto__: Array(0) App.js:30 []length: 0__proto__: Array(0) localhost/:1 Uncaught (in promise) SyntaxError: Unexpected token &lt; in JSON at position 0

标签: json reactjs get fetch


【解决方案1】:

关于您发布的问题 #2,这真的很难说,但是我认为您的卡片列表过于复杂。您应该简单地将一组过滤后的配方传递给您的组件。

您的卡片列表组件应该只将整个配方选项传递给组件,而不是尝试传递特定的道具。如果将来您为每个配方对象添加更多键,您将不必调整您的卡片列表

const CardList = ({recipes}) => {
    return (
        <div>
            {
                recipes.map(recipe => {
                    return <Card recipe={recipe} key={recipe.id} />
                })
            }
        </div>
    )
}

在您的卡片组件中,您可以解构配方对象的键

const Card = ({recipe}) => {
    return (
        <div>
            <h3>{recipe.name}</h3>
            <p>{recipe.type} - {recipe.author}</p>
            <hr />
        </div>
    )
}

我为你做了一个代码沙箱,我使用了 React Hooks 和一个 mockAxios 调用来模拟服务器会做什么,所以如果你想在未来调用 API,你就有了一些代码。 https://codesandbox.io/s/broken-glitter-4wb61?file=/src/App.js

【讨论】:

  • 非常感谢,太棒了。
【解决方案2】:

你不需要使用 fetch 从本地 json 文件中获取数据。

您可以通过以下方式简单地导入./recipedata.json 的内容:

import recipedata from './recipedata.json';

然后将您的 componentDidMount 更改为:

  componentDidMount() {
    this.setState({ recipes: recipedata });
  }

当您尝试从 http 服务器获取数据时,您主要使用 fetch。阅读更多 herehere

为了支持@Qubaish Bhatti 的评论,是的,state 中不需要有recipes。可以直接使用,去掉this.state.recipes

【讨论】:

  • 如果你是直接从文件中导入 JSON,那么不需要设置状态。你可以直接在你的渲染函数中使用。
  • 啊,我明白了。非常感谢您的帮助。
  • @MattFuller 它对你有用吗?如果是,请接受答案。
  • 成功了,谢谢。我现在已经接受了答案。我在第一个帖子编辑中还列出了一个次要问题,如果您能提供任何帮助吗?
  • @MattFuller console.log(recipes) 在您的 CardList 组件中,让我们知道您返回的内容
猜你喜欢
  • 2022-01-11
  • 2022-07-06
  • 2021-09-25
  • 1970-01-01
  • 2021-07-12
  • 2017-12-10
  • 2019-02-05
  • 2021-05-23
  • 1970-01-01
相关资源
最近更新 更多