简体   繁体   English

我如何在 React 中使用 useEffect 仅在组件首次挂载时运行一些代码,而在事件发生时(重复)运行一些其他代码?

[英]How can I use useEffect in React to run some code only when the component first mounts, and some other code whenever an event occurs (repeatedly)?

If the title wasn't clear, I want to run some code when the component mounts, and some other code when a particular variable changes.如果标题不清楚,我想在组件挂载时运行一些代码,并在特定变量更改时运行一些其他代码。 I could add the variable in the [], but the problem is, I want some code to run only once, and not when the variable changes.我可以在 [] 中添加变量,但问题是,我希望某些代码只运行一次,而不是在变量更改时运行。

FYI: The variable is a window property仅供参考:变量是 window 属性

Thanks in advance!提前致谢!

Have two separate effects to handle each case.有两个单独的效果来处理每种情况。

Case 1: when the component mounts案例一:当组件挂载时

useEffect(
  () => {
    // do something
  },
  [] // no dependency: run once
)

Case 2: when the variable changes案例2:当变量发生变化时

useEffect(
  () => {
    if (variable) {
      // do something
    }
  },
  [variable] // with dependency: run every time variable changes
)

暂无
暂无

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

相关问题 React:从 useEffect 调用自定义钩子或在组件挂载之前运行代码 - React: call custom hook from useEffect or run code before component mounts React-Redux:首次安装组件时如何获取数据 - React-Redux: how can i get store data when component first mounts 如何在反应中制作功能组件并使用破坏性分配? (我写了一些代码但没有工作) - How to make a functional Component in react and use destructive assignment? (I wrote some code but not working) 如何在组件卸载上使用 useEffect 钩子来有条件地运行代码 - how to use the useEffect hook on component unmount to conditionally run code React Hooks:具有依赖性的 useEffect 在组件安装时也会被调用 - React Hooks: useEffect with dependecy also called when component mounts 如何在DOM体中渲染组件,即使某些其他组件呈现它的反应? - How can I render a component in DOM body even if some other component renders it in react? 仅在调用者(某些回调)中更改 state 后,如何在 React 功能组件中没有 useEffect 的情况下执行 function? - How to execute the function only after state changed in the caller (some callback) without useEffect in React functional component? 只有在我的 useEffect 代码运行后,我才能返回 children prop in react。 (同步行为) - How can I return children prop in react only after my useEffect code runs. (synchronous behaviour) 反应类组件:如何等到一些代码完成然后渲染? - react class component: how to wait until some code is finished and then render? React 网页仅在我更改某些代码时重新渲染 - React Webpage only re-renders when I change some code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM