使用箭头函数方法从useState调用set函数会过早重新加载



因此,当http请求在自定义挂钩中失败时,我试图在上下文上设置一个数组

这是我的钩子:

const useHttp = (requestObj: any, setData: Function) => 
{
const [isLoading, setIsLoading] = useState(false); 
const ctx = useContext(GlobalContext);

const sendRequest = useCallback(() =>
{
setIsLoading(true);

fetch(requestObj.url, {
method: requestObj.method ? requestObj.method: 'GET',
headers: requestObj.headers ? requestObj.headers : {},
body: requestObj.body ? JSON.stringify(requestObj.body) : null
})
.then(res => res.json())
.then(data => {
setIsLoading(false);
setData(data);                
})
.catch(err => 
{
setIsLoading(false); 
ctx.setErrors([
(prevErrors: string[]) =>
{
//prevErrors.push(err.message)
let newArray = prevErrors.map((error) => {return error});
newArray.push(err.message);
return newArray;
}]
);
console.log('There was an error');
});
}, []);
return {
isLoading: isLoading,
sendRequest: sendRequest
}
} 

Im使用以前的状态值设置数组。我使用.map,因为数组的排列运算符不起作用。我正在调查,但这并不重要。

当它命中setErrors时,似乎会导致重新评估所使用的组件(如下(。我以为在函数启动之前它不会更新。然后的问题是,当它重新评估错误时,第一个元素中包含钩子中的函数的数组。所以我不确定在这里做什么

const App: FC = () => {
const [errors, setErrors] = useState([]);
let modal = null
if(errors.length > 0)
{
modal = ( 
<Modal 
heading="Warning" 
content={<div>{errors}</div>}
buttonList={
[
{label: "OK", clickHandler: ()=> {}, closesModal: true},
{label: "Cancel", clickHandler: ()=> {alert("cancelled")}, closesModal: false}
]
} 
isOpen={true}/>
)
}
return (
<GlobalContext.Provider value={{errors: errors, setErrors: setErrors}}>
<ProviderV3 theme={defaultTheme}>
<Toolbar></Toolbar>
<Grid
margin='25px'
columns='50% 50%'
gap='10px'
maxWidth='100vw'>
<OwnerSearch />
<NewOwnerSearch />
</Grid>
</ProviderV3>
{modal}
</GlobalContext.Provider>
);
};

您不小心在函数周围放置了数组括号:

ctx.setErrors((prevErrors: string[]) => {
//prevErrors.push(err.message)
let newArray = prevErrors.map((error) => {return error});
newArray.push(err.message);
return newArray;
})

最新更新