useEffect 函数在更新二维数组的状态后没有被调用。

huangapple go评论54阅读模式
英文:

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(() =&gt; {
    //this&#39;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&#39;t called (but the state is updated).

This setPieces doesn&#39;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 =&gt; {
         return pieceRow.map( (piece,index) =&gt; {
             const key = `${piece.id}-row-${index}`;
             return piece &amp;&amp; &lt;Piece key={key} piece={piece}/&gt;
         })
     })
``

</details>



huangapple
  • 本文由 发表于 2023年2月20日 00:56:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75501819.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定