如何为 useEffect 中的每个道具调用单独的代码 [英] How to call separate code for every single prop in useEffect

查看:40
本文介绍了如何为 useEffect 中的每个道具调用单独的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作 useEffect 方法,该方法在任何道具更改时调用,但不是所有代码,只有一个专用于此道具

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

推荐答案

您可以使用不同的钩子,并为每个钩子指定一个依赖项.这样,当依赖项更改时,只有特定的 useEffect 会触发:

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

这篇关于如何为 useEffect 中的每个道具调用单独的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆