axios 无法在React中显示获取的API数据

l3zydbqr  于 2023-10-18  发布在  iOS
关注(0)|答案(2)|浏览(163)

我是初学者。我正在开发一个关于React的网站,并使用API来获取数据,但我无法在表视图中显示它。不过,我可以把数据输入控制台。
代码如下:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import "./Hero.css"
import Search from '../../Pages/Search/Search';
import { NavLink } from "react-router-dom";
import { useNavigate } from 'react-router-dom';

const Hero = () => {
    const [item, setItem] = useState('');
    const [unit, setUnit] = useState('');
    const [amazon, setAmazon] = useState(false);
    const [costco, setCostco] = useState(false);
    const [walmart, setWalmart] = useState(false);
    const [dollartree, setDollartree] = useState(false);
    const [data, setData] = useState([]);

    const history = useNavigate();

    const handleInputChange = (event) => {
        setItem(event.target.value);
    };

    const handleUnitChange = (event) => {
        setUnit(event.target.value);
    };

    const handleAmazonChange = (event) => {
        setAmazon(event.target.checked);
    };

    const handleCostcoChange = (event) => {
        setCostco(event.target.checked);
    };

    const handleWalmartChange = (event) => {
        setWalmart(event.target.checked);
    };

    const handleDollartreeChange = (event) => {
        setDollartree(event.target.checked);
    };

    const constructAPIUrl = () => {
    const baseUrl = 'http://74.208.39.34/search';
    const queryParams = [`item=${item}`, `unit=${unit}`];

    // Add vendor query params based on checkbox values
    if (amazon) {
        queryParams.push('amazon=y');
    }

    if (costco) {
        queryParams.push('costco=y');
    }

    if (walmart) {
        queryParams.push('walmart=y');
    }

    if (dollartree) {
        queryParams.push('dollartree=y');
    }

    // Add other vendors as needed (e.g., walmart, dollartree)

    return `${baseUrl}?${queryParams.join('&')}`;
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    const apiUrl = constructAPIUrl();

    // Use Axios to make the API request and fetch data in JSON format
        axios
          .get(apiUrl)
          .then((response) => {
            // Handle the fetched data (e.g., update state to display it in the table)
            setData(response.data);
            console.log(response.data);
            history('/search');
            return response;
          })
          .catch((error) => {
            console.error('Error fetching data:', error);
          });
      };

    return(
<div id="page">
    <div className="container">
        <section className="main-section">
            <div className="flex-row">
                <div className="col-2">
                    <div className="banner-ad">
                        <p>Banner Ad</p>
                    </div>
                </div>
                <div className="col-8">
                    <div className="main-form">
                        <h1>BEST PRICE<br/>LARGEST QUANTITY!</h1>
                        <p>Find the cheapest items for sale online by the pound, ounce, gallon, quart, and more!. From Over Multiple venders </p>
                        <div className="my-form">
                            <form onSubmit={handleSubmit}>
                                <div className="inputs">
                                    <input placeholder="Product name" className="prod-input" name="name" id="name" required="" type="text" value={item} onChange={handleInputChange}/>
                                    <select value={unit} onChange={handleUnitChange} className="unit-select" name="desired_units" id="units" required="">
                                        <option selected="" value="">Select Unit</option>
                                        <option value="count">Count</option>
                                        <optgroup label="Weights &amp; Volumes">
                                            <option value="lb">Pounds</option>
                                            <option value="oz">Ounces</option>
                                            <option value="kg">Kilograms</option>
                                            <option value="g">Grams</option>
                                            <option value="mg">Milligrams</option>
                                            <option value="gal">Gallons</option>
                                            <option value="Liter">Liters</option>
                                            <option value="l">Milliliters</option>
                                            <option value="cups">Cups</option>
                                            <option value="qt">Quarts</option>
                                            <option value="pint">Pints</option>
                                        </optgroup>
                                        <optgroup label="Computer Measurements">
                                            <option value="Terabyte">Terabytes (TB)</option>
                                            <option value="Gigabyte">Gigabytes (GB)</option>
                                            <option value="Megabyte">Megabytes (MB)</option>
                                        </optgroup>
                                    </select>
                                </div>
                                <div className="vendor-ticks">
                                <div className="vendor-head"><h2>VENDORS:</h2></div>
                                    <div className="vendor-tick-box">
                                        <div className="vendor-tick"><input type="checkbox" name="options" id="amazon" checked={amazon} onChange={handleAmazonChange}/><label >AMAZON</label></div>
                                        <div className="vendor-tick"><input type="checkbox" name="options" id="walmart" checked={walmart} onChange={handleWalmartChange}/><label >WALMART</label></div>
                                        <div className="vendor-tick"><input type="checkbox" name="options" id="costco" checked={costco} onChange={handleCostcoChange}/><label >COSTCO</label></div>
                                        <div className="vendor-tick"><input type="checkbox" name="options" id="dollartree" checked={dollartree} onChange={handleDollartreeChange}/><label >DOLLARTREE</label></div>
                                    </div>
                                </div>
                                <div className="submit-btn">
                                    {/* <NavLink to="/search" className="submit-button" type="submit">Check</NavLink> */}
                                    <button type="submit">Check</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <div className="col-2">
                    <div className="banner-ad">
                        <p>Banner Ad</p>
                    </div>
                </div>
            </div>
        </section>
        <section className="brands-logo-section">
            <div className="brands-logos">
                <ul>
                    <li><NavLink to="https://www.amazon.com" target="_blank"><img src="./amazon.png" /></NavLink></li>
                    <li><NavLink to="https://www.walmart.com" target="_blank"><img src="./walmart.png" /></NavLink></li>
                    <li><NavLink to="https://www.costco.com" target="_blank"><img src="./costco.png" /></NavLink></li>
                    <li><NavLink to="https://www.dollartree.com " target="_blank"><img src="./dollartree.png" /></NavLink></li>
                </ul>
            </div>
        </section>
    </div>
    <Search data={data} />
</div>
    )
}

export default Hero;

我在一个JSX组件中获取数据并在另一个组件中显示它。我将数据传递给另一个jsx组件,如下所示:
<Search data={data} />
下面是表格视图组件:

import React from 'react'
import Header from '../../components/Header/Header'
import Footer from '../../components/Footer/Footer'
import './Search.css'

const Search = ({ data }) =>{
        return (
            <div>
              <Header />
              <div id="page">
                <div className="container">
                    <section className="search-result-sec">
                        <div className="flex-row">
                            <div className="col-2">
                             <div className="banner-ad">
                                <p>Banner Ad</p>
                            </div>
                        </div>
                        <div className="col-8">
                            <div className="search-results">
                                {data && data.length > 0 ? (
                                <table>
                                    <thead>
                                        <tr>
                                            <th>Href</th>
                                            <th>Product Name</th>
                                            <th>Price</th>
                                            <th>PPU</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    {data.map((itemData, index) => (
                                    <tr key={index}>
                                        <td>{itemData.href}</td>
                                        <td>{itemData.name}</td>
                                        <td>{itemData.ppu}</td>
                                        <td>{itemData.price}</td>
                                    </tr>
                                    ))}
                                    </tbody>
                                </table>
                                ) : (
                                    <h2>No data available</h2>
                                  )}
                            </div>
                        </div>
                        <div className="col-2">
                         <div className="banner-ad">
                            <p>Banner Ad</p>
                        </div>
                    </div>
                </div>
            </section>
        </div>
        </div>
              <Footer />
            </div>
          )
    }

export default Search

每次当我尝试获取数据时,代码都会将数据记录到控制台并加载下一页,但显示No data Available,因为它没有在此页面中获取任何数据。有人吗请帮帮我我做错了什么。

rsl1atfo

rsl1atfo1#

首先,在Search组件中添加一个console for data,看看是否在那里获得数据。此外,请确保您在data状态下设置了来自响应的正确数据。检查你是否从这段代码的响应中得到一个数组。

axios
          .get(apiUrl)
          .then((response) => {
            // Handle the fetched data (e.g., update state to display it in the table)
            setData(response.data);
            console.log(response.data);
            history('/search');
            return response;
          })

也许response.data返回的是一个包含数组而不是直接包含数组的对象。
如果这还不行,请提供更多的上下文或可能的console.log响应并分享结果。

cgfeq70w

cgfeq70w2#

看起来这个问题可能与获取数据和呈现搜索组件的时间有关。当您使用API获取数据并更新Hero组件中的数据状态时,将导致重新呈现。然而,此时,搜索组件可能已经被呈现而没有接收更新的数据属性。你正在使用history('/search')后设置的数据在这状态.相反,您应该在获取数据并更新状态之后使用history.push('/search')导航到搜索页面

相关问题