我在使用 React 状态数组和钩子时遇到了问题。接收套接字事件时
socket.on("connection request", ({address}) => {
let lastConnection = connections
lastConnection.push({address, actions: <div className="align-right">
<MDBBtn color="success" onClick={() => approveConnection(address, false)}>Approve</MDBBtn>
<MDBBtn color="danger" onClick={() => approveConnection(address, true)}>Refuse</MDBBtn>
</div>})
setConnections([...lastConnection])
})
我更新连接列表。该部分有效,但是当我尝试使用
const approveConnection = (address, banned) => {
console.log("removing address " + address + " from " + connections)
socket.emit("client allow", {address, banned})
let oldConnections = connections
oldConnections = oldConnections.filter(a => a.address !== address)
setConnections([...oldConnections])
}
它工作一次,但是当我尝试删除第二个元素时,第一个删除的元素会弹出回列表中,并且在尝试删除另一个元素时会像这样继续。
你可以帮我吗?
添加连接时,您正在改变状态,这可能是导致错误的原因。而是使用setState
的功能形式:
socket.on("connection request", ({ address }) => {
const connection = {
address,
actions: {
address,
actions: (
<div className="align-right">
<MDBBtn
color="success"
onClick={() => approveConnection(address, false)}
>
Approve
</MDBBtn>
<MDBBtn
color="danger"
onClick={() => approveConnection(address, true)}
>
Refuse
</MDBBtn>
</div>
)
}
};
setConnections(prevConnections => [...prevConnections, connection]);
});
无需复制然后过滤。您可以简单地过滤并将其传递给setConnections
,无需[]
let oldConnections = connections.filter(p => p.address !== address);
setConnections(oldConnections);