Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 更新功能组件中的状态挂钩设置器';身体_Reactjs - Fatal编程技术网

Reactjs 更新功能组件中的状态挂钩设置器';身体

Reactjs 更新功能组件中的状态挂钩设置器';身体,reactjs,Reactjs,我很难找到一个明确的答案,在我的测试中,这种行为似乎不一致。我是否可以直接在函数体中设置状态值(使用useStatehook定义),还是必须使用useffecthook来设置 例如: const Test = () => { // A context provider which provides the window's scroll position. const scrollContext = useContext(ScrollContext); const [scro

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

例如:

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>
  );
};
const Test=()=>{
//提供窗口滚动位置的上下文提供程序。
常量scrollContext=useContext(scrollContext);
const[scrolled,setScrolled]=使用状态(false);
//如果页面滚动超过200像素
//设置为“true”。这有效吗?
如果(!scrolled&&scrollContext.scrollY>200)设置为scrolled(true);
返回(
{滚动的.toString()}
);
};

是,这是有效的!过去,React with类是错误的,请参见-Quote:“您不应该从render调用setState。”)。但是,我在功能组件和钩子的文档中没有看到任何提到这一点的内容。我试图总是在事件侦听器或useEffects回调中设置状态,但除了我在评论中已经链接的内容外,还没有找到其他支持证据。@katamaster818您有此评论的来源吗?是的,这是有效的!过去,React with类是错误的,请参见-Quote:“您不应该从render调用setState。”)。但是,我在功能组件和钩子的文档中没有看到任何提到这一点的内容。我试图总是在事件侦听器或useEffects回调中设置状态,但除了我在评论中已经链接的内容外,还没有找到其他支持证据。@katamaster818您有此评论的来源吗?