0

TestContext.js

 import { createContext } from 'react';

const CheckoutDrawerContext = createContext({
  showDrawer: false,
  toggleCheckoutDrawer: () => {},
});

export default CheckoutDrawerContext;

测试组件.jsx

export default function TestComponent() {

  const checkoutDrawer = useContext(CheckoutDrawerContext);

  function placeOrder() {
    console.log(checkoutDrawer.showDrawer)
      checkoutDrawer.toggleCheckoutDrawer()
    };

  return (
    <div className="cart-drawer__summary">
     <div></div>
      <button type="button" className="order-button" onClick={placeOrder}>
      submit
      </button>
    </div>
  );
};

测试组件1.jsx

export default function TestComponent1() {

  const checkoutDrawer = useContext(CheckoutDrawerContext);

  function placeOrder() {
    console.log(checkoutDrawer.showDrawer)
      checkoutDrawer.toggleCheckoutDrawer()
    };

  return (
    <div className="cart-drawer__summary">
     <div></div>
      <button type="button" className="order-button" onClick={placeOrder}>
      submit
      </button>
    </div>
  );
};

应用程序.js

export default function App() {
  const [showDrawer, setShowDrawer] = useState(false);

  const toggleCheckoutDrawer = () => {
    setShowDrawer(!showDrawer);
  };
    return(
      <Router>
    
    <CheckoutDrawerContext.Provider value={{ showDrawer, toggleCheckoutDrawer }}>
        <Route path="/test" exact component={TestComponent}/>
        <Route path="/test1" exact component={TestComponent1}/>
    </CheckoutDrawerContext.Provider>
        
    </Router>
    );
  }

步骤:打开 http://localhost:3000/ test,点击提交按钮,console.log 打印错误,在不同的选项卡中打开 http://localhost:3000/ test1,点击提交按钮,console.log 打印错误(为什么仍然是假的。是否更改了 TestComponent 中的值?

然后在调用“checkoutDrawer.toggleCheckoutDrawer()”后添加console.log,如下所示,

 function placeOrder() {
    console.log(checkoutDrawer.showDrawer)
      checkoutDrawer.toggleCheckoutDrawer()
    console.log(checkoutDrawer.showDrawer)
    };

现在 console.log 打印 false false。(为什么 checkoutDrawer.toggleCheckoutDrawer() 之后的 console.log 也打印错误?

4

0 回答 0