【问题标题】:How to call separate code for every single prop in useEffect如何为 useEffect 中的每个道具调用单独的代码
【发布时间】:2020-01-19 18:33:43
【问题描述】:

我想做一个 useEffect 方法,当任何 props 改变时调用,但不是所有代码,只是一个专用于这个 props 的代码

我想像这样的事情...... 在这一刻,当一、二或三发生变化时,所有的代码都会被调用。

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]);
}

【问题讨论】:

    标签: reactjs react-hooks use-effect


    【解决方案1】:

    你可以使用不同的钩子,并给它们每个单独的依赖。这样,当依赖项更改时,只有特定的 useEffect 才会触发:

    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;
    }
    

    【讨论】:

    • 完美!谢谢 ;) 我以为我只能使用一次useEffect
    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 2019-11-03
    • 2015-07-14
    • 2019-11-12
    • 2022-08-29
    相关资源
    最近更新 更多