简体   繁体   English

React Hooks useContext 不允许 state 更改

[英]React Hooks useContext not allowing state change

I am using a global state with useContext in React Hooks and get the following error:我在 React Hooks 中使用带有 useContext 的全局 state 并收到以下错误:

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

I want to access and update the state from the context.我想从上下文中访问和更新 state。

My App.js:我的 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 >)
}

My Cart.js (for creating the context):我的 Cart.js(用于创建上下文):

import { createContext } from "react"

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

My Home.js (for accessing the context):我的 Home.js(用于访问上下文):

import { Cart } from '../Cart'

const { cartTotal, setCartTotal } = useContext(Cart)

I cant render right now, something about the object React doesn't like, any ideas?我现在不能渲染,关于 object React 不喜欢的东西,有什么想法吗?

Thanks谢谢

You were close in the initial value for the cart context.您接近购物车上下文的初始值。 It should match the types of the context value you later pass in the provider.它应该与您稍后在提供程序中传递的上下文值的类型相匹配。 Your context value is an object with cartTotal and setCartTotal keys, and the value types are string and function, respectively.您的上下文值是一个 object 和cartTotalsetCartTotal键,值类型分别是字符串和 function。

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

See Updating context from a nested component请参阅从嵌套组件更新上下文

Additionally, you will want to render the Switch within the provider so it is directly rendering the Route components.此外,您将希望在提供程序中呈现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 >
  );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM