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

Jos*_*one 3 reactjs 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)

但问题是zRef.currentundefined第一次渲染时。

对此事的任何意见都非常感激。

jua*_*rco 8

你尝试过吗useMemo

useMemo似乎适合您的用例,因为它允许您仅在依赖项数组中指定的任何一个值发生更改时重新计算值。

就像这样:

const z = useMemo(() => {
    return props.x + props.y
}, [props.x, props.y])
Run Code Online (Sandbox Code Playgroud)