'In React, rendering of array components does not work
After generating the code with create-react-app, we changed App.js to the following code.
After typing in an item input tag, the other elements of the item disappear. Why is this?
import React, { useState, memo, useCallback } from "react";
const isEqual = (prevProps, nextProps) => {
return JSON.stringify(prevProps) === JSON.stringify(nextProps);
};
const InputCell = memo(({ text, onChange }) => {
return <input type="text" value={text} onChange={onChange}></input>;
}, isEqual);
const Item = memo(({ item, setItem }) => {
const onChange = useCallback(
(e) => {
const newItem = { ...item, text: e.target.value };
setItem(newItem);
},
[item, setItem]
);
return (
<li>
{item.id}:
<InputCell text={item.text} onChange={onChange} />
</li>
);
}, isEqual);
const Items = memo(({ items, setItems }) => {
const setItem = useCallback(
(item) => {
const newItems = [...items];
newItems[item.id - 1] = item;
setItems(newItems);
},
[items, setItems]
);
return (
<ul>
{items.map((item) => (
<Item item={item} key={item.id} setItem={setItem} />
))}
</ul>
);
}, isEqual);
const App = React.memo(() => {
const [cnt, setCnt] = useState(1);
const [items, setItems] = useState([{ id: Number(cnt), text: "" }]);
const onClick = useCallback(() => {
setCnt(cnt + 1);
const newItems = [...items];
newItems.push({ id: newItems.length + 1, text: "" });
setItems(newItems);
}, [cnt, items]);
return (
<>
{cnt}
<br />
<button onClick={onClick}>button</button>
<br />
<Items items={items} setItems={setItems} />
</>
);
});
export default App;
I can avoid this problem by not using the isEqual function. However, I would like to use the isEqual function because I want to optimize the drawing if possible.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|