React的`useEffect`在状态更新时执行。

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

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.

huangapple
  • 本文由 发表于 2023年5月7日 04:31:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191002.html
匿名

发表评论

匿名网友

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

确定