React Hooks useContext 不允许状态改变

React Hooks useContext not allowing state change

我在 React Hooks 中使用带有 useContext 的全局状态并收到以下错误:

"Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method."

我想从上下文访问和更新状态。

我的App.js:

import { Cart } from "./Cart"

const App = () => {

  const [cartTotal, setCartTotal] = useState('0');

  return (<BrowserRouter>

    <Switch>

      <Cart.Provider value={{ cartTotal, setCartTotal }}>
        <Route exact path="/" component={Home} />
        <Route exact path="/payment" component={Payment} />
      </Cart.Provider>

    </Switch>
  </BrowserRouter >)
}

我的Cart.js(用于创建上下文):

import { createContext } from "react"

export const Cart = createContext(null) // tried "[[], () => { }]" here instead of null

我的Home.js(用于访问上下文):

import { Cart } from '../Cart'

const { cartTotal, setCartTotal } = useContext(Cart)

我现在无法渲染,React 不喜欢这个对象,有什么想法吗?

谢谢

您接近购物车上下文的初始值。它应该与您稍后在提供程序中传递的上下文值的类型相匹配。您的上下文值是一个带有 cartTotalsetCartTotal 键的对象,值类型分别是字符串和函数。

const Cart = createContext({
  cartTotal: '',
  setCartTotal: () => {},
});

Updating context from a nested component

此外,您需要在提供程序中呈现 Switch,以便它直接呈现 Route 组件。

const App = () => {
  const [cartTotal, setCartTotal] = useState('0');

  return (
    <BrowserRouter>
      <Cart.Provider value={{ cartTotal, setCartTotal }}>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route exact path="/payment" component={Payment} />
        </Switch>
      </Cart.Provider>
    </BrowserRouter >
  );
};