我是新来的反应者,也许这很简单。我有一个似乎无法解决的问题,并且这个问题不断出现。每当我使用map函数对javascript中的数组进行渲染时,我渲染的项目不会一次出现,而是一个接一个地或成块地出现,这取决于一些变化的变量,即旋转木马或手风琴的索引。我总是收到以下警告:
警告:无法在已卸载的组件上执行React状态更新。这是空操作,但它表明应用程序中发生内存泄漏。要修复,请取消使用useEffect清理功能中的所有订阅和异步任务。
我已经在react文档中和以下出色的来源中找到了有关useEffect清理的信息:React Hook - Clean Up useEffect。但是,我发现没有一种解决方案适用于我的用例。有没有人有办法解决吗?以下是手风琴的代码:
//* EXTERNAL IMPORTS
import React, { useState } from 'react'
import styled from 'styled-components'
import { FixedSizeList as List } from 'react-window'
import AutoSizer from 'react-virtualized-auto-sizer'
//* LOCAL IMPORTS
import RowComponent from './RowMenuItem'
import Accordion from '../components/Accordion'
import { ACCORDION_HEIGHT } from '../utils/constants'
//* STYLES
const Container = styled.div`
width: 100%;
height: 99%;
overflow-y: scroll;
`
/**
* * The Menu displays the products of a particular category
* * The display is powered by react-window.
* * React-window is unnecessary for small lists and fast devices,
* * however, for devices with low RAM, it can come in handy.
*/
const Menu = ({ products }) => {
/**
* * Each accordion has an accordionIndex, if that index matches with the
* * state index, then that accordion is displayed
*/
const [index, setIndex] = useState(-1);
//* Getting all unique subcategories in this category
const subCategories = [...new Set(products.map(p => p.subCategory.name))]
return <Container>
{
subCategories.map((subCat, i) => {
/**
* * This function returns a list of all Accordions, each accordion has products
* * belongin to a unique subcategory
*/
const children = (
<AutoSizer>
{({ width }) => (
<List
height={ACCORDION_HEIGHT}
itemCount={products.filter(p => p.subCategory.name === subCat).length}
itemSize={40}
width={width}
itemData={{ products: products.filter(p => p.subCategory.name === subCat) }}
>
{RowComponent}
</List>
)}
</AutoSizer>)
return (
<Accordion
key={i}
category={products[0].category}
subcategory={subCat}
open={index === i}
accordionIndex={i}
components={children}
setIndex={setIndex}
/>)
})
}
</Container>
}
export default Menu
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
警告是在我返回“手风琴”组件的那一行。
类似地,对于滑块,我有一个自定义的钩子,如下所示:
import React from 'react'
import styled from "styled-components"
import { animated } from "react-spring";
const BackImage = animated(styled.img`
filter: blur(10px);
position: fixed;
z-index: 0;
`)
const FrontImage = animated(styled.img`
position: fixed;
z-index: 1;
`)
export default function useAnimatedImages(myImages, isFront) {
const front = myImages.map(im => ({ style }) => (
<FrontImage
src={im.src}
width={im.recommendedWidth}
height={im.recommendedHeight}
style={style}
/>
))
const back = myImages.map(im => ({ style }) => (
<BackImage
src={im.src}
width={1000}
style={style}
/>
))
return isFront ? front : back
};
警告在我返回FrontImage和BackImage的那一行中的tha map函数中。