【问题标题】:React get request without refreshing the page在不刷新页面的情况下响应获取请求
【发布时间】:2021-01-29 13:38:39
【问题描述】:

我有一个应用程序,我首先向端点发出 post 请求,比如说; 端点 A

我有另一个端点,我可以在其中发出 GET HTTP 请求,比如说; 端点 B

现在的问题是如何在不刷新页面的情况下从 ENDPOINT B 获取我发布到 ENDPOINT A 的当前数据。 注意:一切正常,只是我需要刷新页面以查看我发布的当前数据,这不会使其成为反应式应用程序。

这是部分代码

//Get user requests
    useEffect(() => {
        fetch('http://localhost:3002/request/me', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': JSON.parse(localStorage.getItem("Some"))
            }
        }).then(function (res) {
            // console.log(res)
            return res.json()
        }).then(function (datas) {
            setState({ datas: datas })
            console.log(datas)
        }).catch(function (e) {
            console.log(e)
        })
    }, [])

    //Create request
    const onAdd = (data) => {
        fetch('http://localhost:3002/request', {
            method: 'POST',
            headers: {
                'Authorization': JSON.parse(localStorage.getItem("Some"))
            },
            body: data
        }).then(function (res) {
            // console.log(res)
            return res.json()
        }).then(function (data) {
            setPost({datas: data})
            console.log(data)
        }).catch(function (e) {
            console.log(e)
        })
    }

【问题讨论】:

  • 从 ENDPOINT B 获取数据后是否刷新页面?
  • 不,我不想刷新,我只想在不刷新页面的情况下取回数据@Pvkndux

标签: node.js reactjs mongodb express


【解决方案1】:

您可能需要定期轮询服务器。 fetch 请求您只得到一个响应,如果以后数据发生变化,您将不会获得该更新的任何更新,这意味着您需要手动重复请求。

有不同的策略,可能最简单的一种是间隔轮询:

useEffect(() => {
  const performRequest = () => fetch('http://localhost:3002/request/me', ...)
     .then(...)

  const token = setInterval(performRequest, 5000) // Every 5 seconds?
  performRequest(); // Initial request
  return () => {
    // Don't forget to cleanup the interval when this effect is cleaned up.
    clearInterval(token)
  }
}, []);

但是如果你想要更多的控制权,你可以做更多花哨的事情。您可以使用以下 API 在自定义挂钩中编写此逻辑:

const { result, refresh } = useRequestMe()

// When needed, call refresh(). e.g. after a succesful POST request.
const onAdd = (data) => {
        fetch('http://localhost:3002/request', ...)
        .then(function (res) {
            // console.log(res)
            return res.json()
        }).then(function (data) {
            setPost({datas: data})
            refresh();
            console.log(data)
        }).catch(function (e) {
            console.log(e)
        })
    }

【讨论】:

  • 非常感谢您的回答,refresh() @Olivarra1 的值将是什么
猜你喜欢
  • 2017-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-13
  • 1970-01-01
  • 2012-10-30
  • 2017-03-24
相关资源
最近更新 更多