简体   繁体   English

在 onClick 之后反应组件不更新

[英]React component doesn't update after onClick

In my project I have some arrow icons (contained in the Skill component) and when you click on them it changes their className.在我的项目中,我有一些箭头图标(包含在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. 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. The states change correctly but the component does not update the class and rendering takes place (as well as during mounting) only after the first click.状态会正确更改,但组件不会更新 class 并且仅在第一次单击后才会进行渲染(以及在安装期间)。

The page code:页面代码:

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; 

the Skill component code:技能组件代码:

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;

Here the browser console这里是浏览器控制台

You must never mutate a state variable, you must instead create a new reference and update the state variable by calling the updater method.绝不能改变 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM