简体   繁体   English

REACT useEffect() 称为不需要的

[英]REACT useEffect() called unwanted

I'm using useEffect which should update my component whenever the value selected of my state updates:我正在使用useEffect ,每当我的 state selected的值更新时,它应该更新我的组件:

const Thumbnail = ({ image }) => {

    const [state, dispatch] = useContext(Context);
    const [checked, setChecked] = useState(getChecked());

    useEffect(() => {
        setChecked(getChecked())
    }, [state.selected])

...

}
export default Thumbnail

But the Function is called everytime anything in my state is updated.但是每次更新我的 state 中的任何内容时都会调用 Function。 For example when an other component updates state.all , the useEffect() method is being called.例如,当其他组件更新state.all时,将useEffect()方法。

How can I avoit this and only call the useEffect() method when state.selected is being changed?state.selected被更改时,我怎样才能避免这种情况并且只调用useEffect()方法?

I think what you need is useMemo .我认为您需要的是useMemo

useMemo will only recompute the memoized value when one of the dependencies has changed. useMemo只会在依赖项之一发生更改时重新计算记忆值。

const checked = useMemo(() => getChecked(), [state.selected]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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