I was reading the official docs on: https://react.dev/learn/keeping-components-pure#detecting-impure-calculations-with-strict-mode
我正在阅读官方文档:https://react.dev/learn/keeping-components-pure#detecting-impure-calculations-with-strict-mode
It talks about using:
它谈到了如何使用:
<StrictMode>
<App />
</StrictMode>
to guard against functions that are accidentally written not as pure function.
以防止意外编写的不是纯函数的函数。
So I wrote some components that intentionally break the rules:
因此,我编写了一些故意违反规则的组件:
let bar = 1;
function Foo({ hmm }) {
console.log("IN Foo");
bar += Math.random();
hmm += Math.random();
return (
<div>
hmm is {hmm}, bar is {bar}
</div>
);
}
function App() {
console.log("IN APP");
bar += 10 + Math.random();
return (
<>
<div>hi {bar}</div>
<Foo hmm={123} />
<Foo hmm={456} />
</>
);
}
export default App;
However, I cannot get React to warn or give an error about it. So what is the purpose of <StrictMode>
if it doesn't give any warning?
然而,我不能对此作出警告或给出错误的反应。那么,如果
不发出任何警告,它的目的是什么呢?
更多回答
优秀答案推荐
StrictMode
is not meant to provide a warning; rather, it intentionally renders the component twice so that you, the developer, can notice that it might not behave as you intended.
StrictMode不是为了提供警告;相反,它故意呈现组件两次,以便您(开发人员)可以注意到它的行为可能与您的预期不符。
You can see this from the same linked documentation:
您可以从相同的链接文档中看到这一点:
Notice how the original example displayed “Guest #2”, “Guest #4”, and “Guest #6” instead of “Guest #1”, “Guest #2”, and “Guest #3”. The original function was impure, so calling it twice broke it.
更多回答
ok, so this "strictness" is just for you to see something... that's fine. I can accept that. It is just that the new generation of naming that is puzzling to me. "use" this, "use" that, "useEffect"...
好的,这个“严格”只是为了让你看到一些东西……那很好。我可以接受。只是新一代的命名让我感到困惑。“使用”这个“,”使用“那个”,“使用效果”...
@StefanieGauss All hook names start with use
.
@Stefan ieGauss所有挂钩名称都以Use开头。
I know. "use", "hook", these are profound and sublime words
我知道呀。“用”、“钩”,这些都是深奥而崇高的词语。
if there is a hook to make things look prettier, maybe it will be called usePimp
如果有一个钩子可以让东西看起来更漂亮,那么它可能会被称为usePimp
我是一名优秀的程序员,十分优秀!