简体   繁体   English

React 钩子中缺少依赖项的 eslint 警告总是正确的吗?

[英]Are eslint warnings for missing dependencies in React hooks always correct?

I'm wondering if eslint rule for mising dependencies in React hooks is always correct.我想知道在 React 钩子中缺少依赖项的 eslint 规则是否总是正确的。 In my example I have calendarIds object in the state.在我的示例中,我在 state 中有calendarIds object。 When the query is current-day I initialize the calendarIds object to some data.当查询是current-day时,我将calendarIds object 初始化为一些数据。 If the page query params change from curent-day to something else I want to reset the calendarIds object:如果页面查询参数从curent-day更改为其他值,我想重置calendarIds object:

const {calendarData, query} = props
  useEffect(() => {
    console.log('useeffect2');
    if (query['date-range'] === 'current-day') {
      const [currentDay = { events: [] }] = calendarData;
      const events = currentDay.events.reduce((acc, { calendarId, actual, trend }) => {
          acc[calendarId] = { actual: actual || Math.round(Math.random() * 1000),
            trend };
          return acc;
      }, {});

      console.log(CALENDAR_IDS, 'events', events);
      setState({
        type: CALENDAR_IDS,
        payload: events
      });
    } else if (state.realTimeData.calendarIds) {
      setState({
        type: CALENDAR_IDS,
        payload: {}
      });
    }
  }, [calendarData, query]);

The dependencies array includes calendarData and query which trigger the function.依赖数组包括触发 function 的calendarDataquery In the else if I check if I have the calendarIds in the state already, if yes I reset it.else if我检查我是否已经在 state 中有calendarIds ,如果是,我将其重置。

As a result I get a missing dependency for state.realTimeData.calendarIds .结果,我得到了state.realTimeData.calendarIds的缺失依赖项。 However I don't see why this would be a problem to not include it in the dependencies array.但是我不明白为什么不将它包含在依赖项数组中会是一个问题。 On the contrary, it may even trigger an infinite loop of state updates.相反,它甚至可能触发 state 更新的无限循环。

Your useEffect is depending on state.realTimeData.calendarIds being defined which is why you're getting that warning.您的 useEffect 取决于state.realTimeData.calendarIds的定义,这就是您收到该警告的原因。 You're using value outside of the useEffect context.您正在使用 useEffect 上下文之外的值。 You're also overriding your state.realTimeData.calendarIds data with your setState ;您还用您的setState覆盖了您的state.realTimeData.calendarIds数据; not sure if that's intentional.不确定这是否是故意的。 An easy fix is to use a ref for the conditional, so you can rely on not causing an infinite loop.一个简单的解决方法是对条件使用 ref,这样您就可以依靠不导致无限循环。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM