对象作为 React 子对象无效(找到:带有键 {id、firstName、lastName、userName、} 的对象)使用 Axios 从我的 api 获取数据时出现 React 错误

问题描述 投票:0回答:1

我正在尝试将 API 中的数据填充到我的反应表单中。当我

console.log
我的 get 语句时。我可以看到包含信息的数组,这意味着我的 get 正在获取信息。

Image of my console log showing my array of data

现在的问题是尝试使用我返回的这个数组来填充字段 - 而不指定数组编号。

'use client'

import {useEffect, useState } from 'react';
import Axios from "axios";

export default function Page() {
    const [user, setUser] = useState([])

const fetchData = () => { Axios.get('http://localhost:5000/api/v1/users', {
        headers: {
          'Content-Type': 'application/json'
        }, 
      }). then((res) => 
        {
            setUser(res.data)
            console.log(res.data)
        });
    }

   return (
        <div className='tutorial'>
            <h1 className='mb-4 text-2xl'>Data Fetching in React</h1>
            <button onClick={fetchData}>Search</button>
            
            <h2> Base: {JSON.stringify(user)}</h2>
            
        </div>
    )

我需要数组内部的信息,以便我可以举例。通过 API 由用户填充下拉列表或填充名称字段。

我尝试过映射和键控,但无法获得我需要的东西。我也尝试过

headers: {'Content-Type': 'application/json'},

我觉得我已经很接近了,但我只是无法在不指定数组编号的情况下显示和使用我的数据。例如:

Data[0]
Data[1]
。我想要回我的所有数据。

我想要达到一个最终目标,我可以说出我想要的字段

data.firstName
,当我点击搜索按钮时,我可以获得任一用户的名字。

javascript reactjs axios populate
1个回答
0
投票

试试这个。我认为您正在使用 Nextjs。但这就是 React 的方式。出于初始测试目的,您可以使用它。稍后可以修改

import { useEffect, useState } from 'react';
import Axios from "axios";

export default function Page() {
    const [users, setUsers] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);

    useEffect(() => {
        const fetchData = async () => {
            setIsLoading(true);
            try {
                const response = await Axios.get('http://localhost:5000/api/v1/users', {
                    headers: {
                        'Content-Type': 'application/json'
                    },
                });
                setUsers(response.data);
            } catch (error) {
                setError(error.message);
            } finally {
                setIsLoading(false);
            }
        };

        fetchData();

        // Clean-up function
        return () => {
            // Any clean-up code goes here, if needed
        };
    }, []); // Empty dependency array to trigger useEffect only once

    return (
        <div className='tutorial'>
            <h1 className='mb-4 text-2xl'>Data Fetching in React</h1>
            <button disabled={isLoading}> {isLoading ? 'Loading...' : 'Search'}</button>
            {error && <p>Error: {error}</p>}
            <h2>Users:</h2>
            <ul>
                {users.map((user, index) => (
                    <li key={index}>
                        <p>Name: {user.name}</p>
                        <p>Email: {user.email}</p>
                    </li>
                ))}
            </ul>
        </div>
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.