简体   繁体   中英

Why my React component does not rerender when Set state was changed?

Can't get where is the problem hiding. I'm changing state but the component not rerender. So this is my code:

export const InterestsPupup: React.FC = ({interests, title, buttonText}) => {
  const [activeItems, setActiveItems] = useState(new Set())

  const clickOnItemHandler = (item: string) => {
    let newSet = activeItems
    activeItems.has(item) ? newSet.delete(item) : newSet.add(item)
    setActiveItems(prev => newSet)
  }

  return (
        <div className={styles.Container__main}>
            {interests.map((item , index) => {
              return (
                <div
                  key={index}
                  className={activeItems.has(item) ? clsx(styles.item, styles.item_active) : styles.item}
                  onClick={() => clickOnItemHandler(item)}
                >{item}</div>
              )
            })}
        </div>
  );
};

There is my state in shape of Set , i'm changing that state and nothing is happens, only after i reopen that popup component. So my state changes but the component doesn't rerender

You're changing your state in place, you need to ensure you are passing in a new set object and not the same set object reference. Although you've modified the set, you're still passing through the same set object:

setActiveItems(currSet => {
  const newSet = new Set(currSet);
  if(newSet.has(item))
    newSet.delete(item);
  else
    newSet.add(item);
  return newSet;
});

I've replaced the ternary with an if-statement. The conditional operator ? : ? : is generally used when you want to use the value that it returns, however, in your case the value isn't being used, so an if-statement is more appropriate.

你应该这样写:

setActiveItems(newSet);

Someone just wrote a comment that helped and deleted it right after, but thank you The answer was: I just had to change this

let newSet = activeItems

On this:

let newSet = new Set([...activeItems])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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