gpt4 book ai didi

reactjs - REACT JS 如何显示从 onClick 获取的 API 数据?

转载 作者:行者123 更新时间:2023-12-03 14:15:39 25 4
gpt4 key购买 nike

我是初学者,我可以使用map()函数获取和显示API数据对象。现在我尝试创建一个全局获取按钮并使用我获取的 onClick 调用数据。当我使用 console.log 检查 onClick 时,它可以工作,但由于某种原因我无法在浏览器中显示它,并且它没有给我错误。

应用组件

import React, {useState, useEffect} from 'react';
import Recipe from "./Recipe";
import Style from "./style.css"

export default function App() {
const [data, setData] = useState([]);
const [search, setSearch] = useState("");
const [myFilter, setFilter] = useState("chicken");

const recipeApi = {/*recipe api address*/}



const fetchData = () => {
fetch(recipeApi)
.then(res => res.json())
.then(result => setData(result.hits))
.catch(err => console.log("error"))
}

useEffect(() => {
fetchData()
}, [myFilter])


const searching = event => {
setSearch(event.target.value)
}



const mySearch = event => {
event.preventDefault();
setFilter(search);
setSearch("");
}

function deleteHandler(index){
setData(
data.filter((element, filterIndex) => index !== filterIndex)
)
}



console.log(fetchData)

return (
<div className="App">
<button type="submit" onClick = {fetchData}>fetch</button>
<form onSubmit = {mySearch} className = "search-form">
<input className = "search-bar" value = {search} onChange = {searching} />
<button className ="search-button" type="submit">search</button>
</form>

<button type="submit" onClick = {fetchData}>search</button> {/*here I call my fetched data */}

<div className = "recipes"
{data.map((element, index)=>(
<Recipe
onDelete={deleteHandler}
title = {element.recipe.label}
image = {element.recipe.image}
name = {element.recipe.source}
index={index}
key = {index}
calories = {element.recipe.calories}
ingredientLines = {element.recipe.ingredientLines[0]}
/>
))
}
</div>
</div>
);
}

子组件


import React from "react";
import style from "./recipe.module.css"


export default function Recipe({title, image, name, calories, index, onDelete,refetch, ingredientLines}){
return (

<div className = {style.recipe}>
<h3>{title}</h3>
<p>{name}</p>
<p>Calories: {calories}</p>
<p>Ingredients: {ingredientLines}</p>
<img className = {style.image} src = {image} alt="" />
<button type="button" onClick={() => onDelete(index)} className="btn btn-danger">Delete</button>

</div>
)
}

最佳答案

您不应使用索引作为。它可能无法正确更新。

<Recipe
// some props ommitted
key={JSON.stringify(element)}

// if element has an id:
// key={element.id}
/>

关于reactjs - REACT JS 如何显示从 onClick 获取的 API 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61146412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com