繁体   English   中英

获取 json 数据到 state 数组

[英]fetch json data to state array

我获取并获取数据,我想使用 setState 作为数组或 object 将其保存到 state 以便我可以调用返回部分中的每个字段并将其显示在屏幕上

但我收到此错误:

未捕获的错误:对象作为 React 子项无效(找到:object 键 {gender, name, location, email, login, dob, registered, phone, cell, id, picture, nat})。 如果您打算渲染一组孩子,请改用数组

import {useState} from 'react'

export default function Test(){
    const [data, setData] = useState([]);

    const getInfo = async () =>{
        const response = await fetch('https://randomuser.me/api');
        if(response.status === 200){
            const res = await response.json();
            setData(res.results[0]);
            // also try this: setData(res) 
            // also try this: setData(res.result)
        }else{
            throw new Error('Unable to fetch data')
        }
    }
    
    return(
        <div>
            <button onClick={() =>{getInfo()}}>fetch data</button>
            {data}
        </div>
    )
}

请看一下这个代码框 URL,我觉得你可以为你的用例 链接使用 useEffect

问题是您得到的响应不是数组。 您正在尝试在 object 上使用高阶数组方法。 利用,

const resultArray = res.results;

从 JSON 获取结果数组。

似乎res.results[0]是 object ,它具有gendernamelocationemaillogindobregisteredphonecellidpicturenat键。 但是您正在尝试将 state 值data设置为数组。

您应该将数据类型设置为 object。

在渲染 function 以浏览数据时,使用Object.keys()迭代键。


对于onClick在render中的触发方式,不需要() => {getInfo()} ,因为没有具体的参数传递给方法,使用onClick={getInfo}

import {useState} from 'react'

export default function Test(){
    const [data, setData] = useState({});

    const getInfo = async () =>{
        const response = await fetch('https://randomuser.me/api');
        if(response.status === 200){
            const res = await response.json();
            setData(res.results[0]);
            // also try this: setData(res) 
            // also try this: setData(res.result)
        }else{
            throw new Error('Unable to fetch data')
        }
    }
    
    return(
        <div>
            <button onClick={getInfo}>fetch data</button>
            {Object.keys.map(key => (<div>
               {key} : {data.key}
            </div>)}
        </div>
    )
}

从“https://randomuser.me/api”返回的数据不是简单的 JSON 数据。 它实际上是一个 JSON object,其中包含多个子对象,例如“名称”,它再次具有“标题”、“第一个”和“最后一个”作为子对象。 这就是您收到“发现:object with keys”错误的原因。

如果您正在寻找用于测试目的的虚拟数据,我建议您查看“https://jsonplaceholder.typicode.com/”,这是虚拟 JSON 数据的良好来源。

我已经更新了你的代码,它以正确的 JSON 格式返回数据,并且可以分配给 state。

  const getInfo = async () =>{
  const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    
    if(response.status === 200){
        const res = await response.json();
        console.log(res)
        setData(res);        
    }else{
        throw new Error('Unable to fetch data')
    }
}

您的问题可能是您正在使用setData(res.results[0]);

我敢打赌,这是一个 Object 而不是数组。

const [data, setData] = useState([]);

声明 setData function 仅存储 arrays。

尝试使用

const [data, setData] = useState({});

看看这是否有效

如果它不起作用,请给我们输出console.log(res.results)console.log(typeof(res.results[0]))

暂无
暂无

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

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