更新功能组件主体中的状态挂钩设置器

时间:2020-10-29 19:47:47

标签: reactjs

我很难找到一个明确的答案,并且在我的测试中行为似乎不一致。我是否可以直接在函数体内设置状态值(使用useState钩子定义?还是必须使用useEffect钩子来设置状态值?

例如:

const Test = () => {
  // A context provider which provides the window's scroll position.
  const scrollContext = useContext(ScrollContext);

  const [scrolled, setScrolled] = useState(false);

  // If the page has ever been scrolled past 200 pixels 
  // set scrolled to `true`. Is this valid?
  if (!scrolled && scrollContext.scrollY > 200) setScrolled(true);

  return (
     <div>{scrolled.toString()}</div>
  );
};

0 个答案:

没有答案