我试图显示数组项中当前值的img,但在加载时,当我提交我的值时,图像不显示.我提交了两次以显示该值.当更改值并按下Submit时,div不会用新值更新内容,而是重复旧的值.再次提交后,div将更新为新值.
export default function Ingredients() {
const [form, setForm] = useState("");
const [theimg, setheimg] = useState({
name: "",
url: "",
id: "",
});
const [imgArr, setImgArr] = useState([]);
function handleChange(e) {
setForm(e.target.value);
}
function getImg() {
const options = {
method: "GET",
headers: {
"X-RapidAPI-Key": "29a63a7413msh8378b61a2e11cf3p192e62jsn53d83f1651fe",
"X-RapidAPI-Host": "edamam-food-and-grocery-database.p.rapidapi.com",
},
};
fetch(
`https://edamam-food-and-grocery-database.p.rapidapi.com/parser?ingr=${form}`,
options
)
.then((response) => response.json())
.then((response) =>
setheimg((prevImg) => ({
...prevImg,
name: form,
url: response.parsed[0].food.image,
id: Math.random(),
}))
)
.catch((err) => console.error(err));
}
const thingsElements = imgArr.map((thing) => (
<div key={thing.id}>
<img src={thing.url} />
<p>{thing.name}</p>
</div>
));
return (
<>
<Navbar page="/" />
<Heading heading="Ingredients" info="Search by etc" />
<Form
label="Search Ingredients..."
onChange={handleChange}
value={form.value}
imgsrc={theimg}
/>
<button
onClick={() => {
getImg();
setImgArr((oldArray) => {
return [...oldArray, theimg];
});
}}
>
Search
</button>
{thingsElements}
</>
);
}
const Form = (props) => {
return (
<>
<label>
{props.label}
<input value={props.value} onChange={props.onChange} />
</label>
</>
);
};
export default Form;