[英]React with Hooks: how to correctly update state after a click event?
在我的 JSX 中,我通過一組對象(從本地 JS 文件導入)進行映射,以顯示一組帶有鍵、id 和 alt 標記的圖標。
我使用鈎子將狀態設置為空字符串。 我想使用 onClick 事件(傳遞給HeroIcons組件)將此狀態替換為單擊圖標的 ID(該 ID 是一個字符串)。 這是代碼:
import React, { useState } from "react";
import HeroImages from "../images/HeroImages";
import HeroIcons from "../components/HeroIcons";
import HeroShowcase from "../components/HeroShowcase";
const Heroes = () => {
const [hero, currentHero] = useState("");
const setCurrentHero = e => {
currentHero(e.target.id);
console.log(hero);
};
return (
<div className="row">
<div className="col-heroes">
<ul className="hero-list">
{/* map function below */}
{HeroImages.map(({ id, src, altTag }) => (
<HeroIcons
key={id}
id={id}
src={src}
altTag={altTag}
setCurrentHero={setCurrentHero}
/>
))}
</ul>
</div>
<div className="col-showcase">
<HeroShowcase />
</div>
</div>
);
};
export default Heroes;
在 heroIcons 組件內部:
import React from "react";
const HeroIcons = props => {
return (
<li key={props.id} id={props.id} onClick={props.setCurrentHero}>
<img src={props.src} alt={props.altTag} />
</li>
);
};
export default HeroIcons;
單擊圖標(由 map 函數創建)時,id 不會記錄到控制台。 但是,當我瘋狂地多次單擊它時,有時會記錄一個 id。 這給了我一個提示,這個點擊事件可能導致地圖功能重新運行並阻止正常的控制台日志
我該如何解決這個問題?
首先,您必須使用e.currentTarget.id
而不是e.target.id
,這樣您才能獲得當前圖像的id
。
const setCurrentHero = e => {
currentHero(e.currentTarget.id);
console.log(hero);
};
第二個useState
Hook 需要你處理回調以使用log
當前狀態的值,但它不接受像setState
這樣的callback
。 您可以使用useEffect
但最好使用e.currentTarget.id
的值;
這是因為您的hero
在控制台時未更新,因此您需要在更新該值時使用useEffect
掛鈎
const setCurrentHero = e => { currentHero(e.target.id); console.log(hero); }; useEffect(() => { console.log('Hero', hero); }, [hero]);
為什么不直接在渲染中設置值:
<HeroIcons
key={id}
id={id}
src={src}
altTag={altTag}
setCurrentHero={setCurrentHero(id)}
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.