我很难找到一个明确的答案,并且在我的测试中行为似乎不一致。我是否可以直接在函数体内设置状态值(使用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>
);
};