小编Jos*_*one的帖子

Why can't `useCallback` always return the same ref

I don't understand why useCallback always returns a new ref each time one of the deps is updated. It results in many re-render that React.memo() could have avoided.

What is, if any, the problem with this implementation of useCallback?

export function useCallback(callback) {

    const callbackRef = useRef();

    callbackRef.current = callback;

    return useState(() =>
        (...args) => callbackRef.current(...args)
    )[0];

}
Run Code Online (Sandbox Code Playgroud)

Using this instead of the built-in implementation sure has a significant positive impact on performance.

Own conclusion:

There is no reason …

javascript reactjs react-hooks usecallback

8
推荐指数
1
解决办法
274
查看次数

Typescript接口,强制执行额外属性的类型

假设我要创建一个接口来描述这种类型的对象:

let myObj= {
    "count": 3,
    "key1": "foo",
    "key2": "bar",
    "key3": "baz"
};
Run Code Online (Sandbox Code Playgroud)

这些对象始终具有类型编号的属性计数,其余属性为字符串

如果我使用这样的索引签名定义接口:

interface MyObect {
    count: number;
    [key: string]: string;
}
Run Code Online (Sandbox Code Playgroud)

我收到了编译器错误:

[ts] Property 'count' of type 'number' is not assignable to string index type 'string'.
Run Code Online (Sandbox Code Playgroud)

所以我必须这样定义它:

interface MyObect {
    count: number;
    [key: string]: any;
}
Run Code Online (Sandbox Code Playgroud)

但是这个定义并不那么精确。

有没有一种方法可以强制执行额外属性的类型?

types interface typescript

3
推荐指数
2
解决办法
716
查看次数

React hooks:如何仅实例化实例变量一次

我想使用反应钩子从我的道具中获取价值。
我只想计算该值一次,而不是在每次渲染时都计算该值。

这是我想出的第一个解决方案,但如果 props 发生变化,z 不会重新计算。


function App(props: { x: number; y: number }) {
    
    const zRef = useRef<number | undefined>(undefined);

    if( zRef.current === undefined ){
    
        //Let's assume the computation of x + y is costly, I 
        //want to avoid doing it every render.
        zRef.current = props.x + props.y;
    
    }

    return (<span>{zRef.current}</span>);

}
Run Code Online (Sandbox Code Playgroud)

我发现的第二种方法是这样的:


function App(props: { x: number; y: number }) {
    
    const zRef = useRef<number | undefined>(undefined);

    useEffect(()=>{

        zRef.current = props.x + props.y;

    },[props.x, props.y]);

    return (<span>{zRef.current}</span>);

} …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

3
推荐指数
1
解决办法
8020
查看次数