To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function

后端 未结 6 955
无人及你
无人及你 2021-02-03 23:18

I have this code

import ReactDOM from "react-dom";
import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Route         


        
6条回答
  •  自闭症患者
    2021-02-03 23:43

    My case was pretty different from what this questions wants. Still I got the same error.

    My case was because I had a 'list', which was rendered by using .map from array. And I needed to use .shift. (to remove first item in array)

    If array had just one item, it was ok, but since it had 2 of them -> the first one got 'deleted/shifted' and because I used key={index} (while index was from .map), it assumed, that the second item, which later was first, was the same component as the shifted item..

    React kept info from the first item (they were all nodes) and so, if that second node used useEffect(), React threw error, that the component is already dismounted, because the former node with index 0 and key 0 had the same key 0 as the second component.

    The second component correctly used useEffect, but React assumed, that it is called by that former node, which was no longer on the scene -> resulting in error.

    I fixed this by adding different key prop value (not index), but some unique string.

提交回复
热议问题