简体   繁体   English

如何防止在 REACT 钩子中使用状态更新重新渲染?

[英]How to prevent re-render with state update in REACT hook?

(I hope you understand what I want to say although I am not good at English.) (虽然我英文不好,但希望你能明白我想说的话。)

Hello.你好。 I migrate code which is written class component to function component.我将编写类组件的代码迁移到功能组件。 But I have faced several problems like this:但是我遇到了这样的几个问题:

  1. I found no way for migrating shouldComponentUpdate lifecycle.我发现没有办法迁移 shouldComponentUpdate 生命周期。 I know React.memo can handle it like shouldComponentUpdate.我知道 React.memo 可以像 shouldComponentUpdate 一样处理它。 But this way only can be applied on props update.但是这种方式只能应用于道具更新。 I need this process on state update.我需要这个状态更新过程。

  2. When you want to change a few state at once, what do you do for it?当你想一次改变几个状态时,你会怎么做? How can I migrate this code to function component?如何将此代码迁移到功能组件?

    class sample: this.setState({aaa: 'a', bbb: 'b', ccc: 1});类示例: this.setState({aaa: 'a', bbb: 'b', ccc: 1});

    => Do you just call all method? => 你只是调用所有方法吗?

    migration example: setAaa(); setBbb(); setCcc();迁移示例: setAaa(); setBbb(); setCcc(); setAaa(); setBbb(); setCcc();

  3. I don't know how to add callback function with useState.我不知道如何使用 useState 添加回调函数。

    class sample: this.setState({state: value}, ()=> {callback function});类示例: this.setState({state: value}, ()=> {callback function});

    migration exmple: (not solved)迁移示例:(未解决)

Here is sample code that is similar to my code that should be migrated.这是与我应该迁移的代码类似的示例代码。

https://codesandbox.io/s/heuristic-firefly-sq1dm9?file=/src/App.js https://codesandbox.io/s/heuristic-firefly-sq1dm9?file=/src/App.js

I can't attach real code because of security, so I just tried to put all problem that I should solve.由于安全原因,我无法附加真正的代码,所以我只是尝试提出所有我应该解决的问题。

Thank you :)谢谢 :)

useEffect(() => {
// do stuff here

}, [someState]) // will be triggered only when someState changes

useEffect(() => {
// do stuff here

}, []) // will be triggered once on first render

useEffect(() => {
// do stuff here

}) // will be triggered on each render

useEffect(() => {
// do stuff here
const timer = setTimeout(() => console.log('hi'), 5000)
return () => clearTimeout(timer); // you can unsubscribe of any 
// listeners here
}, []) // will be triggered once on first render

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM