简体   繁体   English

如何在 svelte 中使用 useCallback 钩子

[英]how do I use useCallback hook in svelte

This is my code block looks line when used with a useCallback hook in react but I want to use same function in svelte,but want to add this in useCallback hook.这是我的代码块在 react 中与useCallback挂钩使用时的外观,但我想在 svelte 中使用相同的 function,但想在 useCallback 挂钩中添加它。 Is there any alternative for svelte.是否有任何替代苗条。

const newCancelToken = useCallback(() => {
        axiosSource.current = axios.CancelToken.source();
        return axiosSource.current.token;
    }, []);

In Svelte things only update when dependencies are changed by default.在 Svelte 中,只有在默认情况下更改依赖项时才会更新。 You probably should use a reactive statement ( $: ... ) if necessary;如有必要,您可能应该使用反应性语句$: ... ); they can also call functions.他们也可以调用函数。

$: newCancelToken = updateToken(); // Add dependencies as arguments

function updateToken() {
    axiosSource.current = axios.CancelToken.source();
    return axiosSource.current.token;
}

If your function does not have any dependencies, you can just use the function as is.如果您的 function 没有任何依赖项,则可以按原样使用 function。 In Svelte you also can use inline functions in the template without them being re-declared over and over again because the code is analyzed, compiled and optimized.在 Svelte 中,您还可以在模板中使用内联函数,而无需一遍又一遍地重新声明它们,因为代码已经过分析、编译和优化。

Keep that in mind: The way svelte processes its components is very different from react .请记住: svelte 处理其组件的方式与 react 非常不同

React re-renders all components any time any state within a component, or anywhere in a parent, changes.每当组件内的任何 state 或父组件中的任何位置发生更改时,React 都会重新渲染所有组件。 To avoid the re-computation you will need the use of useMemo or useCallback in your case.为避免重新计算,您需要在您的情况下使用useMemouseCallback

Svelte is a compiler and analyzes your template to create targeted DOM update code whenever any concerned state changes. Svelte 是一个编译器,它会分析您的模板,以在任何相关的 state 发生更改时创建有针对性的 DOM 更新代码。 With that in mind, you don't need to memoize such functions with svelte.考虑到这一点,您不需要使用 svelte 来记忆这些功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM