【问题标题】:Next.js Lifting state upNext.js 提升状态
【发布时间】:2021-03-26 10:44:36
【问题描述】:

_app.js

function MyApp({ Component, pageProps }) {
    return (
        <Provider store={store}>      
            <Layout>
                <Component {...pageProps} />
            </Layout>
    );
}

export default MyApp;

Layout.js

function Layout({ children }) {
    const [cartOpen, setCartOpen] = useState(false);
    const handleOpen = () => setCartOpen(!cartOpen);

    return (
        <>
            <Cart cartOpen={cartOpen} handleOpen={handleOpen} />
            <main>{children}</main>
        </>  
    )
}

ProductPage.js

function ProductPage(props) {
    return (
        <div>
            <button onClick={() => console.log('set state to true in cartOpen(defined in layout.js)')}
        </div>
    )
}

在ProductPage 组件内部,它是Layout 的子组件,我希望一个元素有一个OnClick 事件处理程序,它将布局组件中的状态更改为setCartOpen(true)

Link to sandbox

【问题讨论】:

  • 将setCartOpen 或函数作为道具传递给 ProductPage 并在 ProductPage 中调用该函数
  • 或者您可以使用 React Context 使回调在 ProductPage 中可用。

标签: reactjs next.js react-props react-state-management


【解决方案1】:

您可以利用 React Context 使 setCartOpen 可用于树下的任何组件。

import React, { createContext, useState } from 'react';

export const CartContext = createContext(null);

function Layout({ children }) {
    const [cartOpen, setCartOpen] = useState(false);
    const handleOpen = () => setCartOpen(!cartOpen);

    return (
        <CartContext.Provider value={{ cartOpen, setCartOpen }}>
            <Cart cartOpen={cartOpen} handleOpen={handleOpen} />
            <main>{children}</main>
        </CartContext.Provider>  
    )
}

export default Layout;

然后,在您的页面中,从上下文中检索 setCartOpen 并使用它。

import { CartContext } from '<your-path-to>/Layout';

function ProductPage(props) {
    const { setCartOpen } = useContext(CartContext);

    return (
        <div>
            <button onClick={() => setCartOpen(true)}>Open Cart</button>
        </div>
    );
}

export default ProductPage;

【讨论】:

  • 非常感谢,我使用类似的方法解决了查询。我将由 react 管理的状态移动到 redux,这与您的回答中提到的跨组件共享状态的想法相同
  • 谢谢,非常有帮助 我想要按钮显示 {cartOpen} 我将如何更改代码?
  • @JohnMayer 您还需要在上下文提供程序中传递cartOpen:&lt;CartContext.Provider value={{ cartOpen, setCartOpen }}&gt;。然后,您可以通过 ProductPage 组件中的上下文访问它:const { cartOpen, setCartOpen } = useContext(CartContext);。
  • 谢谢!效果很好!
猜你喜欢
  • 2023-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-17
  • 2013-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多