[英]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.我的状态为
Set
,我正在更改该状态并且没有任何反应,只有在我重新打开该弹出组件之后。 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.我已经用 if 语句替换了三元。 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. ? :
通常在您想要使用它返回的值时使用,但是,在您的情况下,该值没有被使用,因此 if 语句更合适。
你应该这样写:
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.