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.
There is no reason …
假设我要创建一个接口来描述这种类型的对象:
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)
但是这个定义并不那么精确。
有没有一种方法可以强制执行额外属性的类型?
我想使用反应钩子从我的道具中获取价值。
我只想计算该值一次,而不是在每次渲染时都计算该值。
这是我想出的第一个解决方案,但如果 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)