代码为:
//i want to send this matrix across to server
const [matrix, setMatrix] = useState([
['', '', ''],
['', '', ''],
['', '', ''],
]);
//fn handler whr matrix is sent to server through socket.emit
const updateGameMatrix = (column, row, symbol) => {
const newMatrix = [...matrix];
if (newMatrix[row][column] === "" || newMatrix[row][column] === null) {
newMatrix[row][column] = symbol;
setMatrix(newMatrix);
}
console.log("matrix outside update_game: " , newMatrix) //prints the array
socket.emit("update_game", ( newMatrix ) => {
console.log("update game matrix: ", newMatrix) //does not print anyt?
setPlayerTurn(false);
});
};
在服务器端;update_game";发射的:
socket.on("update_game", (newMatrix) => {
console.log("MATRIX FOR UPDATE_GAME: ", newMatrix) //printed: MATRIX FOR UPDATE_GAME: [Function (anonymous)]
setPlayerTurn(false)
});
});
为什么套接字接收我的矩阵作为一个匿名函数?
因为您没有发送矩阵-您错误地使用了.emit()
来发送数据。在.emit()
中使用回调函数仅适用于您希望从另一端进行确认时,而不适用于发送数据。此代码将发送矩阵数据:
socket.emit("update_game", newMatrix);
并且,客户端中的此代码将接收它:
socket.on("update_game", (newMatrix) => {
console.log("MATRIX FOR UPDATE_GAME: ", newMatrix);
});