响应与 React 中的获取 API 不匹配

问题描述 投票:0回答:0

我正在使用自定义挂钩来包装获取 api 从端点提取数据。但是,完全不相关的请求的响应不匹配,这意味着一个 api 的响应被注入到另一个请求中:

这就是我使用 fetchAPI 的方式:

export const useFetch = (url, requestId, body) => {
    const [state, setState] = useState({isLoading: true, data: []})
    const [version, setVersion] = useState(0)

    const getData = async () => {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(body),
            cache: 'no-store' // disable caching
        });
        const json = await response.json() 
        if (response.status === 200)
            return json
        else throw new Error(`Server Exception occurred. Status code: ${response.status} & Exception: ${json.exception}`)
    }

    useEffect(() => {
        setState({isLoading: true, data: []})
        getData()
            .then((data) => {
                setState(previousState => {
                    return { ...previousState, isLoading: false, data: data }
                });
            })
            .catch((err) => {
                console.log(err)
                addNotification(requestId, 'danger', 'Error', 'An error occurred.', 'top-right')
                setState(previousState => {
                    return { ...previousState, isLoading: false, data: [] }
                });
                // setError(true)
            }).finally(() => {
                console.log(`${requestId} completed...`)
        });
    }, [version]);

    return {isLoading: state.isLoading, data: state.data, version, setVersion}
}

钩子的使用方法如下:

const {isLoading, data} = useFetch(URL_GET_SESSION.constructUrl, 'GET_SESSION', {})

尽管我也使用了 cache: 'no-store' 并尝试通过附加 ?requestId=requestId 使请求唯一,但我仍然能够偶尔复制该问题。

这可能是什么原因?

执行本身是否存在问题。我还没有嵌入 AbortController。

reactjs fetch-api browser-cache http-caching react-custom-hooks
© www.soinside.com 2019 - 2024. All rights reserved.