如何在对mongodb进行get请求调用时防止重复的fetch请求

gk7wooem  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(75)

我遇到了一个问题。我做了一个get请求,并多次获得结果。我已经从indexjs中删除了strictmode。第一个月

const token = localStorage.getItem('token')
        if (token !== null) {
            try {
                const chat = await axios.get('http://localhost:5500/api/chat', {
                    headers: {
                        "Authorization": `Bearer ${token}`
                    }
                })
                console.log(chat.data.fetchChat);
                setFetchChat(chat.data.fetchChat)
            } catch (err) {
                console.log(err);
            }
        }else{
            navigate('/login')
        }
    }
    useEffect(()=>{
        allChat()
    },[])```

My indexJs file

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css'

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render( <App />)

字符串

wpcxdonn

wpcxdonn1#

您可以尝试在发出GET请求之前添加一个条件。下面是一个例子:

const [hasFetched, setHasFetched] = useState(false); // add this state

  async function allChat() {
    const token = localStorage.getItem('token')
    if (token !== null && !hasFetched) { // check if we have fetched before
      try {
        const chat = await axios.get('http://localhost:5500/api/chat', {
          headers: {
            "Authorization": `Bearer ${token}`
          }
        })
        console.log(chat.data.fetchChat);
        setFetchChat(chat.data.fetchChat)
        setHasFetched(true); // set hasFetched to true after fetching
      } catch (err) {
        console.log(err);
      }
    } else {
      navigate('/login')
    }
  }

  useEffect(() => {
    allChat()
  }, [])

字符串
在上面的代码中,我只在发出GET请求后才将hasFetched设置为true。这样,如果组件重新呈现,我就可以避免再次发出请求,因为hasFetched现在为true。

相关问题