【问题标题】:js async function executed when referenced引用时执行的js异步函数
【发布时间】:2021-11-21 10:03:46
【问题描述】:

我试图引用一个异步函数,但它却被执行了。

const Payment = props => {
    const [buttonAction, setButtonAction] = useState(null);

    useEffect(() => {
        if(some true stuff){
            // this gets executed instead of being a reference to a function
            setButtonAction(() => createSubscription(a ? b : c ));
        }
    }, [deps...]);

    const createSubscription = async (sessionId) => {
        // code
    }
}

【问题讨论】:

    标签: javascript reactjs asynchronous


    【解决方案1】:

    React 的 useState setter 函数接受:

    • 要设置的数据,或
    • 使用最新版本数据调用的函数(请参阅文档中的 here),该函数将返回要设置的数据

    通过将函数传递给 setButtonAction,您要求 React 使用最新值 buttonAction 调用该函数,以便您可以更新它。

    您不能直接将函数存储在这样的状态中,并且通常没有理由这样做(尽管存在边缘情况)。

    一些替代方案:

    • 如果您确实需要在状态中存储函数,请将其包装在一个对象中。
    • 使用useCallbackuseMemo 重用函数,仅在其依赖关系发生变化时更新它
    • 请将其保存在 ref 中。

    【讨论】:

    • useCallback 适合我正在编写的逻辑。我最终使用了 useRef();常量 buttonAction = useRef(null); SETTING buttonAction .current = () => createSubscription(a?b : c);调用 onClick={() => professionalButtonAction.current()} 。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    相关资源
    最近更新 更多