【问题标题】:How to preserve value in react component even when the component updates and rerenders即使组件更新和重新渲染,如何在反应组件中保留价值
【发布时间】:2021-03-14 16:36:15
【问题描述】:

即使组件已更新和重新渲染,我也想在反应组件中保留一个值。我通常将它存储在父组件中,但在这种情况下,父组件也会更新,所以这不是一个选项。

在以下示例中,我需要保留 div 元素的 scrollTop 位置。 我这样做的方法是将值存储在全局变量中。有没有办法不使用全局变量?

import React, { useRef, useEffect } from 'react';
import ItemsList from './ItemsList';

const ItemsListContainer = (props) => {
    let elementRef = useRef(null);

    useEffect(() => {
        elementRef.current.scrollTop = window['scrollPos'];
    });

    function storeScrollPosition() {
        window['scrollPos'] = elementRef.current.scrollTop;
    }

    return (
        <div className="items-list-container" ref={elementRef} onScroll={storeScrollPosition}>
            <ItemsList context={props.context}></ItemsList>
        </div>
    )
}

export default ItemsListContainer;

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:
    let elementRef = useRef(null);
    
    useEffect(() => {
        elementRef.current.scrollTop = window['scrollPos'];
    });
    

    通过这样做,您将在每次渲染时设置 scrollTop 值。 如果您想保留该值,请改用 useMemo

    const myValue = useMemo(() => {
     return window['scrollPos'];
    },[]);
    

    空数组意味着 useMemo 没有依赖关系,因此只会在第一次评估它


    使用上下文:

    export const CustomContext = React.createContext({});
    
    export const App: React.FC = () => {
      const [value, setValue] = useState()
      return <CustomContext.Provider value={{ value, setValue }}>
           //wrapped code
        </CustomContext.Provider>;
    };
    

    在您可以访问的任何子组件中

    const { value, setValue } = React.useContext(CustomContext);
    
    useEffect(() => {
        setValue(window['scrollPos'])
    });
    

    使用本地商店

    看看lockr

    Lockr.set('value', window['scrollPos'];)
    Lockr.get('value');
    

    【讨论】:

    • 我需要在每次渲染时设置 scrollTop。这是目标。我的问题是如何在不使用全局变量的情况下存储 scrollTop 的值。
    • 你的选择是:redux(但我不是粉丝),上下文(你可以用它包装你的应用程序,但如果你重新加载你的应用程序,价值将丢失),本地商店在这种情况下值可以随时使用。这可能是一个选择吗?
    • 我已经用更多细节更新了答案
    猜你喜欢
    • 2020-02-25
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多