简体   繁体   English

获取 json 数据到 state 数组

[英]fetch json data to state array

I fetch and get the data, I want to save it to state using setState as an array or object so I can call to each field in the return part and display it on screen我获取并获取数据,我想使用 setState 作为数组或 object 将其保存到 state 以便我可以调用返回部分中的每个字段并将其显示在屏幕上

but I get this error:但我收到此错误:

Uncaught Error: Objects are not valid as a React child (found: object with keys {gender, name, location, email, login, dob, registered, phone, cell, id, picture, nat}).未捕获的错误:对象作为 React 子项无效(找到:object 键 {gender, name, location, email, login, dob, registered, phone, cell, id, picture, nat})。 If you meant to render a collection of children, use an array instead如果您打算渲染一组孩子,请改用数组

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>
    )
}

Please have a look at this codesandbox URL, I feel you can make use of useEffect for your usecase link请看一下这个代码框 URL,我觉得你可以为你的用例 链接使用 useEffect

The problem is your are getting an response which is not an array.问题是您得到的响应不是数组。 You are trying to use higher order array methode on a object.您正在尝试在 object 上使用高阶数组方法。 Use,利用,

const resultArray = res.results;

get the array of results from the JSON.从 JSON 获取结果数组。

It seems like res.results[0] is the object that has the keys of gender , name , location , email , login , dob , registered , phone , cell , id , picture , nat .似乎res.results[0]是 object ,它具有gendernamelocationemaillogindobregisteredphonecellidpicturenat键。 But you are trying to set the state value data as an array.但是您正在尝试将 state 值data设置为数组。

You should set the data type to object.您应该将数据类型设置为 object。

In render function to browse the data, iterate the keys using Object.keys() .在渲染 function 以浏览数据时,使用Object.keys()迭代键。


for the onClick triggering way in render, you don't need to () => {getInfo()} since there is no specific parameters passed to the method, just use onClick={getInfo} .对于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>
    )
}

The data being returned here from "https://randomuser.me/api" is not a simple JSON data.从“https://randomuser.me/api”返回的数据不是简单的 JSON 数据。 It is really a JSON object with multiple sub-objects in it such as "name", which is again having "title", "first" and "last" as sub-objects.它实际上是一个 JSON object,其中包含多个子对象,例如“名称”,它再次具有“标题”、“第一个”和“最后一个”作为子对象。 This is the reason you are getting error that "found: object with keys".这就是您收到“发现:object with keys”错误的原因。

If you are looking for dummy data for testing purpose, I would suggest you to check "https://jsonplaceholder.typicode.com/", which is a good source of dummy JSON data.如果您正在寻找用于测试目的的虚拟数据,我建议您查看“https://jsonplaceholder.typicode.com/”,这是虚拟 JSON 数据的良好来源。

I have updated your code as under, which is returning data in proper JSON format and can be assigned to state.我已经更新了你的代码,它以正确的 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')
    }
}

Your problem might be that you are using setData(res.results[0]);您的问题可能是您正在使用setData(res.results[0]);

I bet that this is an Object and not an Array.我敢打赌,这是一个 Object 而不是数组。

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

states that the setData function only stores arrays.声明 setData function 仅存储 arrays。

try using尝试使用

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

and see if that is working看看这是否有效

if it is not working give us the ouput of console.log(res.results) and console.log(typeof(res.results[0]))如果它不起作用,请给我们输出console.log(res.results)console.log(typeof(res.results[0]))

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

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