我应该在哪里声明在useEffect()挂钩内调用的函数? [英] Where should I declare functions that are called inside a useEffect() hook?

查看:31
本文介绍了我应该在哪里声明在useEffect()挂钩内调用的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当使用 useEffect 调用依赖于状态的函数时,我会遇到以下情况.

So I have the following situation when using a useEffect that calls a functions that depends on state.

示例:

// INSIDE APP COMPONENT

const [someState, setSomeState] = React.useState(0);
const [someTrigger, setSomeTrigger] = React.useState(false);

function someFunction() {
  return someState + 1;  
}

React.useEffect(() => {

  const newState = someFunction();  // 'someFunction' IS BEING CALLED HERE
  setSomeState(newState);

},[someTrigger])

问题:

在这种情况下,我应该在 useEffect()内声明 someFunction 还是将其保留在外部(但位于组件的内部)是否安全?

In this case, should I declare someFunction inside the useEffect() or is it safe to keep it outside (but inside component's body)?

我可以将其添加到 dependency 数组中,但这会损害代码的可重复性,因为我想专注于 trigger .

I could add it to the dependency array, but it will hurt the redability of my code, since I want to focus on the trigger.

由于 useEffect()将在新的渲染后运行,因此可以安全地假定它具有我在其中调用的函数的新副本吗?

Since the useEffect() will run after a fresh render, is it safe to assume that it will have fresh copies of the functions that I'm calling inside of it?

是否存在基本规则,即何时应在 useEffect 挂钩内声明函数,或者何时必须将其添加到依赖项数组中?

Is there a basic rule of when you should declare functions inside the useEffect hook or when is it mandatory that you add it to the dependency array?

编辑:请注意, useEffect 必须具有这些功能的新副本,因为这些功能需要访问一些最新的状态变量.

Note that it's necessary that the useEffect has fresh copies of those functions, since those functions need to access some fresh up-to-date state variable.

注意:

此代码在CodeSandbox上触发以下退出警告.虽然效果很好.

This code triggers the following eslint warning on CodeSandbox. Although it works just fine.

React Hook React.useEffect缺少依赖项:'someFunction'.包括它或删除依赖项数组.(反应钩/穷举滴水)软垫

React Hook React.useEffect has a missing dependency: 'someFunction'. Either include it or remove the dependency array. (react-hooks/exhaustive-deps)eslint

真实案例场景:

这是一个简化的示例.实际上,这是一个包含过滤器组件的产品搜索页面.因此,当我单击一个过滤器以激活它(例如, price< = 50 )时,我正在触发一个 useEffect(),它正在监听" activePriceFilters 状态变量.然后,该效果调用一个函数(示例中为 someFunction ),该函数将计算 filteredList 并将使用新的设置新的 productList 状态> filteredList .

This is a simplified example. In my real case, this is a product search page with filters components. So when I click on a filter to activate it (let's say, price <= 50), I'm triggering a useEffect() that is "listening" for the activePriceFilters state variable. That effect then calls a function (someFunction in the example) that will calculate the filteredList and will set the new productList state with the new filteredList.

SNIPPET

function App() {
  
  const [someState, setSomeState] = React.useState(0);
  const [someTrigger, setSomeTrigger] = React.useState(false);
  
  function someFunction() {
    return someState + 1;  
  }
  
  React.useEffect(() => {
  
    const newState = someFunction();
    setSomeState(newState);
  
  },[someTrigger])
  
  return(
    <React.Fragment>
      <div>I am App</div>
      <div>My state: {someState}</div>
      <button onClick={()=>setSomeTrigger((prevState) => !prevState)}>Click</button>
    </React.Fragment>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

推荐答案

在useEffect之内或之外定义函数的决定取决于调用所有函数的位置.

A decision to define a function within or outside of useEffect depends on where all the functions is called.

如果仅在useEffect中调用您的函数,则有必要在useEffect中定义它.

If your function is called only from within the useEffect then it makes sense to define it within the useEffect.

但是在useEffect以及其他事件处理程序或其他效果中正在调用相同的函数,您需要在useEffect之外定义它

However is the same function is being called from within useEffect as well as other event handlers or other effects, you need to define it outside of useEffect

PS.在您的情况下,您只是在更新不需要定义单独功能的状态

PS. in your case you are just updating the state for which you needn't define a separate function

function App() {
  
  const [someState, setSomeState] = React.useState(0);
  const [someTrigger, setSomeTrigger] = React.useState(false);
  

  React.useEffect(() => {
    setSomeState(oldState => oldState + 1);
  
  },[someTrigger])
  
  return(
    <React.Fragment>
      <div>I am App</div>
      <div>My state: {someState}</div>
      <button onClick={()=>setSomeTrigger((prevState) => !prevState)}>Click</button>
    </React.Fragment>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

就您的情况而言,您会这样写

As far as you scenario is concerned, you would write it like

useEffect(() => {
    const calcVal = (oldState) => {
         // calculate previous state based on oldState
    }

    setSomeState(calcVal);
}, [activePriceFilters])

这篇关于我应该在哪里声明在useEffect()挂钩内调用的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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