[英]React component doesn't update after onClick
在我的項目中,我有一些箭頭圖標(包含在Skill
組件中),當您單擊它們時,它會更改它們的類名。 To check if the component has been clicked I used a boolean array as state, so when the onClick event is fired it toggle the state of the component. 狀態會正確更改,但組件不會更新 class 並且僅在第一次單擊后才會進行渲染(以及在安裝期間)。
頁面代碼:
import { useState, useEffect } from 'react';
import Skill from '../../components/skill/skill.component';
import { skills } from './skills';
import './about-page.styles.scss';
const AboutPage = () => {
console.log('render')
const [cache, setCache] = useState([]);
useEffect(() => {
setCache(new Array(skills.length).fill(false))
}, []);
const onToggleFunc = n => {
cache[n] = !cache[n];
setCache(cache);
console.log(cache);
}
return (
<div className='about-page'>
<div className='container'>
{
skills.map((x, i) => (
<Skill
isToggled={cache[i]}
skillName={x.name}
onClickFunc={() => (onToggleFunc(i))}
key={i}
/>
))
}
</div>
</div>
)
}
export default AboutPage;
技能組件代碼:
import './skill.styles.scss';
import icon from '../../assets/icons/arrow.png';
const Skill = ({ isToggled, skillName, onClickFunc }) => (
<div className='skill-item'>
<img src={icon} alt='icon'
className={`icon ${isToggled ? 'toggled' : '' }`}
onClick={onClickFunc}
/>
<span className='desc'>{skillName}</span>
</div>
)
export default Skill;
這里是瀏覽器控制台
您絕不能改變 state 變量,而必須創建一個新引用並通過調用 updater 方法更新 state 變量。
const AboutPage = () => {
const [cache, setCache] = useState(() => new Array(skills.length).fill(false));
function onToggleFunc(n) {
// create a new array from the previous one
setCache(prevCache => prevCache.map((val, i) => i !== n ? val : !val));
}
return (
<div className='about-page'>
<div className='container'>
{
skills.map((x, i) => (
<Skill
key={i}
isToggled={cache[i]}
skillName={x.name}
onClickFunc={() => onToggleFunc(i)}
/>
))
}
</div>
</div>
)
}
export default AboutPage;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.