useContext或多次调用useEffect?

我有一个自定义的useEffect挂钩,用于获取每分钟的当前时间。

const useDateStatus = () => {
  const [date,setDate] = useState(new Date());

  useEffect(() => {
    const interval = setInterval(() => {
      setDate(() => new Date());
    },60000); 
    return () => clearInterval(interval);
  },[]);

  return date;
};

我需要一个通用组件,当日期在给定的时间范围内时,该组件将呈现null,否则它将显示date

const DateAlert = ({timeRanges,children}) => {
  const date = useDateStatus();

  if (!inRanges(date,timeRanges)) {
    return null;
  }

  return (
    <Alert>
      <p>{date}</p>
      {children}
    </Alert>
  );
};

我还需要另一个不需要date对象的通用组件。

const Display = ({timeRanges,timeRanges)) {
    return null;
  }

  return children;
};

我是否应该创建一个包含date的上下文,以便传递date道具,然后使DateAlert使用该上下文?

const context = React.createContext(new Date());
const DateContext = ({children}) => {
  const date = useDateStatus(new Date);
  return (
    <context.Provider value={date}>
      {children}
    </context.Provider>
  );
}

我需要从How to pass props to {this.props.children}获取date状态,我认为最好使用上下文将date作为道具传递给孩子。

使用上下文获取date或直接调用useDateStatus()获取日期和有什么区别?

还是有更好的方法来减少DateAlertDisplay之间的冗余?

dciyy 回答:useContext或多次调用useEffect?

我建议制作一个组件,然后将其用于两个组件,例如:

const RenderIfInRange = ({timeRanges,children}) => {
  const date = useDateStatus();

  if (!inRanges(date,timeRanges)) {
    return null;
  }

  return children;
};

这将成为您的Display组件。然后:

const DateAlert = ({children}) => (
    <RenderIfInRange>
      <Alert>
        <p>{date}</p>
        {children}
      </Alert>
    </RenderIfInRange>
  );

我建议您调查Truefit's Bach。它使您可以将HOC模式用于钩子,并让代码看起来更加整洁。

本文链接:https://www.f2er.com/3148981.html

大家都在问