为什么在更新数组内容后,我的映射函数需要提交两次才能显示更新后的状态



我试图为数组项中的当前值显示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;

在您的点击处理程序中,在将theimg添加到数组之前,您不需要等待getImg()完成。

试试这样的东西,而不是

const getImg = async () => {
const params = new URLSearchParams({ ingr: form });
const res = await fetch(`https://example.com/parser?${params}`, {
method: "GET",
headers: {
"X-RapidAPI-Key": "<api-key>",
"X-RapidAPI-Host": "<host>",
},
});
if (!res.ok) {
throw res;
}
const data = await response.json();
return {
name: form,
url: data.parsed[0].food.image,
id: Math.random(), // recommend Date.now() instead
};
};
const clickHandler = async () => {
try {
const newImg = await getImg(); // wait for getImg() to resolve
settheimg(newImg); // set img state
setImgArr((prev) => [...prev, newImg]); // add it to the array
} catch (err) {
console.error(err);
}
};

在你的<button>。。。

<button onClick={clickHandler}>Search</button>

最新更新