【问题标题】:Add item from Fetch API to Array and Displaying new array in React将项目从 Fetch API 添加到数组并在 React 中显示新数组
【发布时间】:2022-11-24 14:22:11
【问题描述】:

我是第一次学习 React,我有一个应用程序可以从公共 API 获取一些数据。我目前让它显示 10 张带有来自 API 的随机项目的卡片,我添加了一个按钮来从 API 中获取随机项目并将其添加到数组中,我设法使用 push() 将新项目添加到数组中但它不会显示在应用程序本身中。我怎样才能使新项目也显示在应用程序中?

这是我的代码

首页.js

import { useState, useEffect} from "react";
import Card from './Card';
const Home = () => {

    const [animals, setAnimals] = useState([]);

    const handleDelete = (id) => {
        const newAnimals = animals.filter(animal => animal.id !== id);
        setAnimals(newAnimals);
    }

    useEffect(() => {
        fetch('https://zoo-animal-api.herokuapp.com/animals/rand/10')
        .then(res => {return res.json()})
        .then(data => {
            setAnimals(data);
        });
    }, []);

    const handleAddAnimal = () => {
        fetch('https://zoo-animal-api.herokuapp.com/animals/rand/')
        .then(res => {return res.json()})
        .then(data => {
            animals.push(data);
            console.log(animals);
            //what to do after this
        })
    }

    return (
        <div className="home">
            <h2>Animals</h2>
            <button onClick={handleAddAnimal}>Add Animal</button>
            <Card animals={animals} handleDelete={handleDelete}/>
        </div>
      );
}

 
export default Home;

卡片.js

const Card = ({animals, handleDelete}) => {
    // const animals = props.animals;

    return (  
        <div className="col-3">
        {animals.map((animal) => (
            <div className="card" key={animal.id}>
            <img
                src={animal.image_link}
                alt={animal.latin_name}
                className="card-img-top"
            />
            <div className="card-body">
                <h3 className="card-title">{animal.name}</h3>
                <p>Habitat: {animal.habitat}</p>
                <button onClick={() => handleDelete(animal.id)}>Delete Animal</button>
            </div>
        </div>
            ))}
    </div>
    );
}
 
export default Card;

应用程序.js

import Navbar from './navbar';
import Home from './Home';

function App() {

  return (
    <section id="app">
      <div className="container">
      <Navbar />
      <div className="row">
        <Home />
      </div>
      </div>
    </section>
  );
}

export default App;

让我知道是否还有其他我应该添加的内容,我们将不胜感激,谢谢!

【问题讨论】:

    标签: javascript reactjs arrays typescript react-hooks


    【解决方案1】:

    而是使用 array.push() 方法。您尝试使用

    setTheArray([...theArray, newElement]);例如,在您的情况下,您的 onClick 事件中将是 setAnimals([...animals,data]) 。

    让我知道它是否解决了您的问题。

    【讨论】:

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