简体   繁体   English

React Hook useEffect 缺少依赖“消息”

[英]React Hook useEffect has a missing dependency "messages"

I am trying to use MERN for the first time but now I am stuck with this code that returns the above mentioned warning and though the compilation works but some activities are missing.我第一次尝试使用 MERN,但现在我被这个返回上述警告的代码困住了,尽管编译工作正常,但缺少一些活动。 I am attaching my part of the code along with this.我附上了我的部分代码。

import React, { useEffect, useState } from "react";
import "./App.css";
import Chat from "./Chat";
import Sidebar from "./Sidebar";
import Pusher from 'pusher-js';
import axios from './axios'

function App() {
  const [messages, setMessages] = useState([])

  useEffect(() =>{
    axios.get('/messages/sync').then((response) => {
      setMessages(response.data)
    })
  }, [])

  useEffect(() => {
    const pusher = new Pusher('----------------', {
      cluster: '^^^'
    });

    const channel = pusher.subscribe('message');
    channel.bind('inserted',(newMessage) => {
      alert(JSON.stringify(newMessage));
      setMessages([...messages, newMessage])
    });
  }, [])

  console.log(messages)

  return (
    <div className="app">
      <div className="app_body">
        <Sidebar />
        <Chat />
      </div>
    </div>
  );
}

export default App;

This is the console output:这是控制台 output:

Compiled with warnings.

./src/App.js
  Line 27:6:  React Hook useEffect has a missing dependency: 'messages'. Either include it or remove the dependency array. You can also do a functional update 'setMessages(m => ...)' if you only need 'messages' in the 'setMessages' call  react-hooks/exhaustive-deps

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

I am trying to build this app with a online video tutorial but this is the problem that occurs to me.我正在尝试使用在线视频教程构建此应用程序,但这是我遇到的问题。 How to fix this issue?如何解决这个问题?

Because you are using state messages in useEffect .因为您在useEffect中使用 state messages You just using function when call setMessages to update state like this:您只需在调用setMessages时使用 function 来更新 state ,如下所示:

setMessages(preMessages => ([...preMessages , newMessage]))

Neither of the current existing answers explain why this is necessary.当前现有的答案都没有解释为什么这是必要的。

The useEffect hook can be run in 3 scenarios: useEffect挂钩可以在 3 种情况下运行:

  • useEffect(fn) is run every time your component renders每次渲染组件时都会运行useEffect(fn)
  • useEffect(fn, []) is run the first time your component mounts useEffect(fn, [])在组件第一次挂载时运行
  • useEffect(fn, [var1, var2]) is run initially, and then any time either var1 or var2 changes. useEffect(fn, [var1, var2])最初运行,然后任何时候var1var2更改。

The reason you are getting the warning is that the linter has detected you are using an outside dependency ( messages ) in your function, however it's not listed as an explicit dependency.您收到警告的原因是 linter 检测到您在 function 中使用了外部依赖项( messages ),但是它没有被列为显式依赖项。 As such, if messages were to change, the useEffect would have a stale version and it would likely cause bugs.因此,如果要更改messages ,则useEffect将具有过时的版本,并且可能会导致错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM