我刚开始反应,并在 use effect 钩子内初始化了一个名为 socket 的变量。我试图在我的退货声明中访问它。但是我似乎无法访问它。我不知道该怎么做。提前致谢!
O(kn²)
答案 0 :(得分:1)
您可以在组件外部定义变量或在 then 函数内部声明它并在 useEffect 内部为其赋值。
function SendSocketData(socket) {
socket.emit("hello", "world");
}
let socket;
function App() {
useEffect(()=> {
socket = io("http://localhost:3001",)
}, []);
return (
<div className="App">
<button onClick={()=>SendSocketData(socket)}>Send Data </button>
</div>
);
}
export default App;
或
function App() {
let socket;
useEffect(()=> {
socket = io("http://localhost:3001",)
}, []);
return (
<div className="App">
<button onClick={()=>SendSocketData(socket)}>Send Data </button>
</div>
);
}
答案 1 :(得分:1)
进入:
function App() {
const socket = io("http://localhost:3001",
);
useEffect(()=> {}
或使用useState:
function App() {
const [socket, setSocket ] = useState(null);
);
useEffect(()=> {
setSocket(io("http://localhost:3001"));
}
答案 2 :(得分:1)
您首先需要使用 useState()
将套接字对象声明为变量:
import React, { useState, useEffect } from 'react';
const [socket, setSocket] = useState(null);
然后用 useEffect()
赋值:
useEffect(()=> {
setSocket(io("http://localhost:3001"));
},[]);
答案 3 :(得分:1)
您可以尝试将套接字存储在可变状态。像这样:
import React, { useState, useEffect } from "react";
import io from "socket.io-client";
function App() {
const [socket, setSocket] = useState();
useEffect(() => {
setSocket(io("http://localhost:3001"));
}, []);
function SendSocketData(socket) {
socket.emit("hello", "world");
}
return (
<div className="App">
<button onClick={()=>SendSocketData(socket)}>Send Data </button>
</div>
);
}
export default App;