英文:
useEffect function not called after updating state of a 2d array
问题
我有一个2D数组的状态,其中包含以以下方式呈现的对象:
```jsx
<div id="pieces">
{
//棋盘上的棋子
pieces.map(pieceRow => {
return pieceRow.map(piece => {
return piece && <Piece key={piece.id} piece={piece}/>
})
})
}
</div>
useEffect函数位于Piece组件中:
function Piece({piece}){
const pieceRef = useRef(null);
useEffect(() => {
//这是useEffect函数,其中piece是通过props传递给组件的2D数组的对象
...
}, [piece])
return ...
当我更新状态,将一个元素从一行移动到另一行时,useEffect被调用:
newPieces[3][0] = null;
newPieces[4][0] = obj;
[obj.x, obj.y] = [4, 0]
setPieces(newPieces);
这段代码有效,但如果我尝试将元素移动到同一行的另一个位置,useEffect不会被调用(但状态已经更新)。
这个setPieces不会调用useEffect:
newPieces[3][0] = null;
newPieces[3][1] = obj;
[obj.x, obj.y] = [3, 1]
setPieces(newPieces);
有什么建议吗?
<details>
<summary>英文:</summary>
I have a 2d array state full of objects rendered like this:
<div id="pieces">
{
//pieces of the board
pieces.map(pieceRow => {
return pieceRow.map(piece => {
return piece && <Piece key={piece.id} piece={piece}/>
})
})
}
</div>
The useEffect function is in the Piece Component:
function Piece({piece}){
const pieceRef = useRef(null);
useEffect(() => {
//this's the useEffect function, where piece is the obj of the 2d array passed by props to the component
...
}, [piece])
return ...
When i update the state moving an element from a row to another row the useEffect is called:
newPieces[3][0] = null;
newPieces[4][0] = obj;
[obj.x, obj.y] = [4, 0]
setPieces(newPieces);
This piece of code works, but if i try to move the element to another position in the same row the useEffect isn't called (but the state is updated).
This setPieces doesn't call the useEffect:
newPieces[3][0] = null;
newPieces[3][1] = obj;
[obj.x, obj.y] = [3, 1]
setPieces(newPieces);
Any suggestion?
</details>
# 答案1
**得分**: 0
这是因为该片段的ID相同。因此,React不会重新渲染组件。尝试在键中包含行信息。这样,当将片段移动到其自己的行内时,组件将重新渲染。
```js
pieces.map(pieceRow => {
return pieceRow.map( (piece,index) => {
const key = `${piece.id}-row-${index}`;
return piece && <Piece key={key} piece={piece}/>;
})
})
英文:
It is because the id of the piece is the same. So React do not re-render the component. Try to include the row in the key. This way the component will re-render when the piece is moved inside its own row.
pieces.map(pieceRow => {
return pieceRow.map( (piece,index) => {
const key = `${piece.id}-row-${index}`;
return piece && <Piece key={key} piece={piece}/>
})
})
``
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论