React / Redux自定义中间件-useDispatch不更新状态

问题描述

我想创建一些中间件来检查令牌的expires_at字段,必要时刷新令牌并更新令牌字段的状态。

我已经使用redux工具包来创建redux功能,并使用了slices。我有一个切片,它将使用令牌数据更新状态,并且可以在初始令牌的回调中使用。

创建中间件时,我无法调用该切片,因此状态保持不变。

作为没有api调用的简单尖峰:

import { useSelector,usedispatch } from 'react-redux';
import { setTokens } from '../features/tokens/tokenSlice';

const refresher = () => ({ dispatch,getState }) => (next) => (action) => {
    const exp_at = useSelector((state) => state.tokens.expires_at);

    if(hasBreachedThreshold(exp_at)){
        dispatch = usedispatch();
        dispatch(
            setTokens({
            access_token: 'new token',expires_at: 637423776000000000,-- hard coded date way in the future.
        })
    }
    
    ... else carry on.
);

我希望在调用中间件时,在第一次通过hasBreachedThreshold()返回true时,dispatch方法调用slice reducer并更新状态。任何进一步的运行都会过去,因为hasBreachedThreshold()会返回false-仍然会持续一段时间。

发生的事情是,hasBreachThreshold始终返回false,因为状态从未更新,从而导致不确定的循环。

中间件已正确配置并被调用。 从状态中提取expires_at值。 已经对hasBreachThreshold()进行了全面测试,并且行为正常。

对React / Redux相当陌生,我希望我对如何以及何时使用dispatch的理解是错误的。我以为我可以像在组件中一样使用调度,不是这样吗?还是我完全以错误的方式来做这件事?

解决方法

编写中间件时,您已经具有dispatch函数和Redux存储available through the function params

// Use `dispatch` & `getState`
const refresher = () => ({ dispatch,getState }) => (next) => (action) => {
    const exp_at = getState().tokens.expires_at;

    if(hasBreachedThreshold(exp_at)){
        dispatch(
            setTokens({
            access_token: 'new token',expires_at: 637423776000000000,-- hard coded date way in the future.
        })
    }
);

此外,您还有何时使用React钩子的本质错误,请参阅Rules of Hooks

在Redux中间件的上下文中钩子不可用。