How to call separate code for every single prop in useEffect

走远了吗. 提交于 2020-01-05 03:48:28

问题


I would like to make useEffect method, which is calling when any prop is changed but not all the code, just a single one dedicated for this props

I imagine something like that ... In this moment all the code is called whed one, two or three is changed.

const SomethingComponent = (props: any) => {
   const {one, two, three} = props;

   useEffect(() => {
      if(something for one props){
         code for one
      }

      if(something for two props){
         code for two
      }

      if(something for three props){
         code for three
      }
   }, [one, two, three]);
}

回答1:


You can use different hooks, and give each of them a single dependency. This way only that specific useEffect will fire when the dependency changes:

const SomethingComponent = (props: any) => {
    const { one, two, three } = props

    useEffect(() => {
        // code for one
    }, [one])

    useEffect(() => {
        // code for two
    }, [two])

    useEffect(() => {
        // code for three
    }, [three])

    return null;
}


来源:https://stackoverflow.com/questions/57998905/how-to-call-separate-code-for-every-single-prop-in-useeffect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!