首页 > 解决方案 > 在一个组件中使用值并在另一个组件中重置

问题描述

我有一个简单的 ReactJS 组件,它使用一些状态,myValue存储在上下文中。

在这个页面上,我myValue用一些 HTML 和一个按钮呈现。

我希望在 HTML 中呈现的原始值myValue,但我想将上下文中的值设置为 0。

该按钮应始终显示上下文中保存的值,该值应在页面上呈现为 0。

export function MyComponent() {
    const { myValue, setMyValue } = useContext(myValueContext);

    useClearData(); // Should be called somewhere to reset myValue to 0

    return (
        <React.Fragment>
            <MyValueButton /> {/* Should display myValue as 0 */}
            <main className="App">
                <div>
                    My value is the original {myValue} which should be non-zero!
                </div>
            </main>
        </React.Fragment>
    );
}

如何构造此代码,以便在上下文更改时重新呈现按钮,但 HTML 不会?

标签: javascriptreactjs

解决方案


所以,要回答我自己的问题,这需要useRef钩子:

export function MyComponent() {
    const { myValue, setMyValue } = useContext(myValueContext);
    myValueRef = useRef(myvalue);
    useClearData(); // Should be called somewhere to reset myValue to 0

    return (
        <React.Fragment>
            <MyValueButton /> {/* Should display myValue as 0 */}
            <main className="App">
                <div>
                    My value is the original {myValueRef.current.toString()} which should be non-zero!
                </div>
            </main>
        </React.Fragment>
    );
}

推荐阅读