[Pit encountered in learning react: memory leak error]

The pit encountered in learning react: memory leak error

对就是这个错误
Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
I found a bunch of blogs on the Internet, and they all said that it was asynchronous problems, such as clearing the timer before the component was destroyed, but my problem was not like this, my error was not due to asynchronous, but the component logic in react caused by rendering

I know you don't like to read code, so I won't post it [Manual dog head]

1. I use the Sanmu operator in my page to control the display of that component (some of them are mixed components)

2. Then the variable of the condition judged by Miki uses a state defined by useState

3. I gave him an initial value in this state, which can match a component

4. Use useEffect in the page during initialization, get the parameters of the address bar and assign them to this state.
If the parameters of the address bar are the same as the default value of the state at the beginning, this error will not occur, but if they are different, the above will be reported a bunch of mistakes

Problem solved:

Instead of the Sanmu operator, use the && short-circuit union operator to independently judge the rendering of their own components, and then assign the default value of the initial state to null (that is, it does not match any components at the beginning, and the ts project pays attention to the generic state of the state, of course not It must be null, as long as it is a value that has nothing to do with component rendering)

Then save and run again to refresh, experiment, etc., and successfully eliminate the error

Guess you like

Origin blog.csdn.net/weixin_54645575/article/details/124676939