简体   繁体   English

如何确保仅在调用 API 后才加载 React 组件?

[英]How can I ensure that a React component is loaded only after some API call has been made?

I have a App component as below and it has MyHeaderComponent as it's child.我有一个 App 组件,如下所示,它有 MyHeaderComponent 作为它的孩子。

On MyHeaderComponent load, I invoke a service call/endpoint.在 MyHeaderComponent 加载时,我调用服务调用/端点。 However, I want to ensure that MyHeaderComponent itself is invoked only after callSomeServiceEndpoint has finished.但是,我想确保仅在 callSomeServiceEndpoint 完成后才调用 MyHeaderComponent 本身。 Not sure if that is possible, since the call to /myrefresh is an opaque response (just returning me a cookie)不确定这是否可能,因为对 /myrefresh 的调用是一个不透明的响应(只是返回一个 cookie)

function App() {
    const [url, setUrl] = useState({});
    const urls = useMyFetch('api/myApiURLs', {});
    const [isEntitled, setIsEntitled] = useState(false);

    useEffect(() => {
        if (Object.keys(urls).length > 0) {
            setUrl(urls);
            callSomeServiceEndpoint(urls);
        }
    }, [urls])

    return (
        <>
            <MyContextProvider>
                <MyHeaderComponent url={urls} />                
            </MyContextProvider>
        </>
    );
}

export default App;

Below is callSomeServiceEndpoint下面是 callSomeServiceEndpoint

export default function callSomeServiceEndpoint(myURLs) {
    const int = 1 * 60 * 1000;
    function myrefresh(myURLs) {
        Object.values(myURLs).forEach((myURL) => {
            fetch(`${myURL}/myapi/myrefresh`, {
                mode: 'no-cors',
                credentials: 'include'
            });
        });
    }
    myrefresh(myURLs);
    const refInterval = setInterval(myrefresh, int, myURLs);
    window.addEventListener("beforeunload", function () {clearInterval(refInterval)});
}

Below is useMyFetch下面是useMyFetch

import {useEffect, useState} from 'react';

export default function useMyFetch(url, data) {
    const [url] = useState(url);
    const [mydata, setMyData] = useState(data);
    useEffect(() => {
        fetch(url, {mode: 'no-cors', credentials: 'same-origin'})
            .then(response => {
                // Response handling and setMyData()
            })
            .catch(error => {                
            });
    }, [url]);

    return data;
}

What do you think about a boolean in custom hook triggered in in fetch's then ?您如何看待在 fetch 中触发的自定义挂钩中的then Something like:就像是:

import {useEffect, useState} from 'react';

export default function useMyFetch(url, data) {
    const [url] = useState(url);
    const [mydata, setMyData] = useState(data);
    const [isDone, setIsDone] = useState(false); //<-- boolean here
    useEffect(() => {
        fetch(url, {mode: 'no-cors', credentials: 'same-origin'})
            .then(response => {
                // Response handling and setMyData()

                setIsDone(true); //<-- set to true
            })
            .catch(error => {                
            });
    }, [url]);

    return [mydata, isDone];
}

And the App component:和 App 组件:

function App() {
    const [url, setUrl] = useState({});
    const [urls, isDone] = useMyFetch('api/myApiURLs', {});
    const [isEntitled, setIsEntitled] = useState(false);

    useEffect(() => {
        if (Object.keys(urls).length > 0) {
            setUrl(urls);
            callSomeServiceEndpoint(urls);
        }
    }, [urls])

    return (
        <>
            <MyContextProvider>
                {isDone && <MyHeaderComponent url={urls} />}  //<-- conditional rendering             
            </MyContextProvider>
        </>
    );
}

export default App;

You may create a state like const [endpointCalled, setEndpointCalled] = useState(false);你可以创建一个 state 像const [endpointCalled, setEndpointCalled] = useState(false); in the App component.App组件中。

Then change callSomeServiceEndpoint so that it returns a promise in order to rewrite it like然后更改callSomeServiceEndpoint以便它返回 promise 以便重写它

callSomeServiceEndpoint(urls).then(setEndpointCalled(true));

and finally最后

<>
 <MyContextProvider>
  {endpointCalled ? <MyHeaderComponent url={urls} /> : null}                
 </MyContextProvider>
</>

暂无
暂无

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

相关问题 如何在加载URL后才调用revokeObjectURL? - How can I call revokeObjectURL only after the URL has loaded? 仅在Angular中发出$ http请求后,才能运行javascript函数? - How can I run a javascript function only after a $http request has been made in Angular? 即使组件树没有更改,我如何确保React创建组件的新实例? - How can I ensure that React creates a new instance of a component, even if the component tree has not changed? 如何仅在 iframe 完全加载后显示页面? - How do i display a page ONLY after the iframe has been loaded completely? 加载元素时或之后调用函数 - Call function if or after an element has been Loaded 完全加载jQuery元素后,如何执行click事件? - How can I execute a click event after a jQuery element has been completely loaded? 日历完全加载后,如何在全日历上呈现事件? - How can I render events on fullcalendar after the calendar has been loaded completely? jQuery对话框窗口加载后,如何更改按钮或可用按钮的功能? - How can I change the buttons OR function of available buttons on a jQuery dialog window after it has been loaded? 在通过异步 API 调用加载数据后,如何呈现数据并初始化 UI 事件处理? - How to render data and initialize an UI event handling upon this data after the data has been loaded by an asynchronous API call? 卸载组件后如何调用函数? - How to call a function after a component has been unmounted?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM