[英]Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak. cancel all subscriptions an
I am passing props from a child nested inside a class component我从嵌套在 class 组件内的孩子传递道具
class Viewer extends React.Component {
....
render(){
return(
.....
<DragAndDrop characters={characters}/>
)
}
to the parent functional component到父功能组件
function DragAndDrop(props) {
console.log("char",props.characters); # I am able to console.log this
const [characters, updateCharacters] = useState(props.characters); # but doing this throws an error
function handleOnDragEnd(result) {
if (!result.destination) return;
const items = Array.from(characters);
const [reorderedItem] = items.splice(result.source.index, 1);
items.splice(result.destination.index, 0, reorderedItem);
updateCharacters(items);
}
return (
<div className="App">
<header className="App-header">
<h1>Final Space Characters</h1>
<DragDropContext onDragEnd={handleOnDragEnd}>
<Droppable droppableId="characters">
{(provided) => (
<ul
className="characters"
{...provided.droppableProps}
ref={provided.innerRef}
>
{characters.map(({ id, name, thumb }, index) => {
return (
<Draggable key={id} draggableId={id} index={index}>
{(provided) => (
<li
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
<div className="characters-thumb">
<img src={thumb} alt={`${name} Thumb`} />
</div>
<p>{name}</p>
</li>
)}
</Draggable>
);
})}
{provided.placeholder}
</ul>
)}
</Droppable>
</DragDropContext>
</header>
</div>
);
}
export default DragAndDrop;
but when I pass props.characters
to useState, it throw an error, How I can resolve this?但是当我将
props.characters
传递给 useState 时,它会抛出一个错误,我该如何解决这个问题? thanks谢谢
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak. cancel all subscriptions an
This problem take place because you initialize state before mount component.出现此问题是因为您在安装组件之前初始化了 state。 If you want to correct your component you can use useEffect inside your component and inside that updateCharacters like below
如果要更正组件,可以在组件内部和 updateCharacters 内部使用 useEffect ,如下所示
useEffect(()=>{
updateCharacters(props.characters);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.