【问题标题】:How to render a list from a JSON url? - ReactJS hooks如何从 JSON url 呈现列表? - ReactJS 钩子
【发布时间】:2020-12-14 19:26:04
【问题描述】:

我想从JSON URL 呈现一个列表。但是,我有以下错误:对象作为 React 子对象无效(发现:TypeError:无法获取)。如果您打算渲染一组孩子,请改用数组。我哪里出错了?谢谢你的回答

//hooks.tsx
import { useEffect, useState } from 'react'

export const useFetch = () => {

  const [data, setData] = useState([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)

  useEffect(() => {

    setLoading(true)
    setError(null)

    fetch('https://jsonkeeper.com/b/Z51B')
      .then(res => res.json())
      .then(json => {
        setLoading(false)
        if (json.data) {
          setData(json.data)
        } else {
          setData([])
        }
      })
      .catch(err => {
        setError(err)
        setLoading(false)
      })
  }, [])
  return { data, loading, error }
}

//index.tsx
import React from 'react';
import { useFetch } from "./hooks.js";
import {CardItem} from './card';

export const List = () => {
    
    const { data, loading, error } = useFetch()

    if (loading) return <div>Loading...</div>
    if (error) return <div>{error}</div>

    return (
      <>
            <ul>
                {data.map((item: any, index: any) => (
                    <li key={index}>
                        {item.names.map((name: any) => {
                            return <CardItem
                                family={item.family}
                                name={name}
                        />
                        })
                        }
                    </li>
                ))}
            </ul>
      </>
    );
  };

【问题讨论】:

  • 请检查您运行map() 的变量dataitem.names。也许您期望数组,但它们是对象

标签: javascript json reactjs list fetch


【解决方案1】:

我想问题出在您的自定义钩子的catch 块中的setError(err)。应该是setError(err.message)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-14
    • 2020-06-14
    • 2020-07-02
    • 2021-12-29
    • 2020-08-04
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    相关资源
    最近更新 更多