英文:
React useEffect executes every time the state is updated
问题
以下是您提供的React组件代码的翻译部分:
const App = () => {
let webSocket = new WebSocket(WS_URL);
const [image, setImage] = useState({});
const [bannerName, setBannerName] = useState('');
const [bannerId, setBannerId] = useState(0);
useEffect(() => {
webSocket.onopen = (evt) => {
console.log('On open web socket: ', evt);
}
webSocket.onmessage = (evt) => {
console.log('SERVER DATA: ', evt.data);
}
console.log('Ready state: ', webSocket.readyState);
}, []);
const updateImage = (evt) => {
setImage(evt.target.files[0]);
}
const updateBannerName = (evt) => {
setBannerName(evt.target.value);
}
const updateBannerID = (evt) => {
setBannerId(Number(evt.target.value));
}
}
请注意,我已经忽略了您提供的问题,只翻译了您的React组件代码。如果您有任何其他疑问或需要进一步的帮助,请随时提出。
英文:
In my React component I have the following code (I'm gonna exclude the return statement because it's not relevant for this case):
const App = () => {
let webSocket = new WebSocket(WS_URL);
const [image, setImage] = useState({});
const [bannerName, setBannerName] = useState('');
const [bannerId, setBannerId] = useState(0);
useEffect(() => {
webSocket.onopen = (evt) => {
console.log('On open web socket: ', evt);
}
webSocket.onmessage = (evt) => {
console.log('SERVER DATA: ', evt.data);
}
console.log('Ready state: ', webSocket.readyState);
}, []);
const updateImage = (evt) => {
setImage(evt.target.files[0]);
}
const updateBannerName = (evt) => {
setBannerName(evt.target.value);
}
const updateBannerID = (evt) => {
setBannerId(Number(evt.target.value));
}
}
As I understand, if I use the useEffect()
hook with an empty dependency array, it should be executed just once (it should work like a componentDidMount
when using class components).
The problem is that it's being executed every time I update the state properties. Does anyone know what am I missing here?
Thank you!
答案1
得分: 1
我注意到每次 App 组件代码运行时都会创建一个新的 WebSocket(例如,每次更新状态变量时都会这样)。您是否真的打算这样做?
否则,请更改您的代码,使WebSocket只创建一次。
英文:
I do note that you create a new WebSocket every time the App component code runs (and that is every time you update a state variable for example). Do you really mean to do this?
Otherwise change your code so that the WebSocket is only created once.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论