gpt4 book ai didi

Cannot get React to complain about a non-pure function(无法做出反应来抱怨非纯函数)

转载 作者:bug小助手 更新时间:2023-10-26 20:02:24 33 4
gpt4 key购买 nike



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.

UnloadMode并不意味着提供警告;相反,它故意呈现组件两次,以便开发人员可以注意到它可能不按预期运行。


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"...

好吧,那么这个“严”就是让你看到一些东西。没关系我可以接受。只是新一代的命名方式让我感到困惑。“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

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com