【发布时间】:2021-07-15 22:45:00
【问题描述】:
我在 .tsx 文件中有以下自定义挂钩:
import {useCallback, useState} from 'react';
const useHttp = (requestObj: any, setData: Function) =>
{
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [elements, setElements] = useState(null);
const sendRequest = useCallback(() =>
{
setIsLoading(true);
setError(null);
fetch(requestObj.url)
.then(res => res.json())
.then(data => {
setIsLoading(false);
setData(data);
let jsx = (<div>Testing conor</div>)
setElements(jsx);
})
.catch(err =>
{
setError(err.message);
setIsLoading(false);
console.log('There was an error');
});
}, []);
return {
isLoading: isLoading,
error: error,
elements: elements,
sendRequest: sendRequest
}
}
export default useHttp;
当我调用 setElements 时,我的 IDE 说我调用 setElements 时出错。
let jsx: JSX.Element
Argument of type 'Element' is not assignable to parameter of type 'SetStateAction<null>'.
Type 'Element' provides no match for the signature '(prevState: null): null'.ts(2345)
代码运行良好,所以我只想知道为什么 ide 说它有问题
【问题讨论】:
-
@EmileBergeron 我正在为 http 请求制作自定义挂钩。如果它失败了我想要一个模态显示我希望钩子负责制作那个模态所以每个使用钩子的地方都不需要使用它的组件
-
这不是应该的。在这种情况下,上下文和提供者会更有意义,因为提供者可以根据当前上下文(http 的东西)注入 JSX,而钩子可能只是一个上下文使用者/设置者。
-
@EmileBergeron 抱歉,如果我要说的话很愚蠢,我是全新的反应,所以请多多包涵。在这种情况下,在上下文中,我需要为每个 http 调用或错误数组或其他内容指定一个特定字段,因为我在加载时屏幕上有多个组件,如果其中一些组件失败,我需要显示所有错误。我说的对吗?
-
您对处理所有不同可能请求的复杂性有一个很好的观点,并且您遇到了一种 XY 问题,其中通用请求挂钩可能不是解决方案,但我们需要更多信息在实际用例上告诉你更多。如果您想在获取错误时显示模态,那么上下文中的简单错误数组可能足以显示通知用户失败的通用模态。
标签: reactjs