A note about not firing side effects in useState(prev => next) ?
还没有人认领这个 Issue。
- 主要语言
- JavaScript
- 星标
- 11.8k
- 派生
- 7.9k
- 平均合并
- 1 天 11 小时
- 30 天内合并 PR
- 11
描述
So I ended up doing this by mistake after a wonky merge:
let Foo = (props) => {
let [bar, setBar] = useState();
let handleClick = () => {
useState(bar => {
let newBar = bar + 1;
props.handleBarChange(newBar); // bad, which isn't surprising
return newBar;
});
};
return <div onClick={handleClick}>click me</div>;
};
If you fire a side effect such as calling something that sets state in a higher component from a useState updater function, you get the error "Cannot update a component from inside the function body of a different component" (but not always! It seems to depend on internal timing). This definitely seems like a bad idea when you look at it, but I couldn't find any mention in the docs that this is bad.
https://reactjs.org/docs/hooks-reference.html#functional-updates
There is the note about side effects generally on useEffect:
Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase)
But this is not in the main body of a function component, doesn't feel like a true side effect as it's still just setting state within React, and doesn't feel like it's in the render phase either.
I initially wanted to comment about this here (https://github.com/facebook/react/issues/18178), because the general message of that thread was "don't set state of another component in a render method", and I've managed to get this error message without doing that, but the thread is locked. Thanks.
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从链接的 Hooks 参考页面开始,尤其是函数式更新部分,并将其中的指导与引用的关于 useEffect 副作用的说明进行比较。明确 useState updater 中的副作用是否不受支持,并解释相关行为;当文档能够毫无歧义地说明这个示例时,即视为完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- javascript, react
- 领域
- documentation
- Issue 类型
- 文档
- 难度
- 2/5
- 预计耗时
- 1-3 小时
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 45/100