简体   繁体   English

在映射的父组件中反应 useState

[英]React useState within mapped parent component

Im new to React and im trying to understand useState.我是 React 的新手,我正在尝试理解 useState。 So im pulling in an array of products and then mapping the array to display each product card:所以我拉入了一个产品数组,然后映射该数组以显示每个产品卡片:

export default function ProductList({ products }) {

  return (
        <Grid templateColumns='repeat(3, 1fr)' columnGap={6} rowGap={10}>
          {
            products.map(product => (
              <ProductCard key={product.node.id} product={product} productID={product.node.id} />
            ))
          }
        </Grid>
  )
}

and inside of my ProductCard I have a bunch of useState , to handle product options, variants, etc.在我的ProductCard中,我有一堆useState ,用于处理产品选项、变体等。

const [available, setAvailable] = useState(true)
const [selectedVariant, setSelectedVariant] = useState('')
const [selectedOptions, setSelectedOptions] = useState('')
const { addToCart } = useContext(CartContext)

So my question is, do each of the ProductCard actually share the same useState, even though they are being mapped?所以我的问题是,每个ProductCard是否实际上共享相同的 useState,即使它们正在映射?

You map collection of separate components, they won't share logic or state. State is hermetic and other components wont have access to it unless allowed to.您 map 是独立组件的集合,它们不会共享逻辑或 state。State 是密封的,除非允许,否则其他组件将无法访问它。

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

相关问题 如何从React组件中的映射项中设置状态 - How to setState from within a mapped item within React component 无法使用 React UseState 更新父组件 state - Can't update parent component state with React UseState 无法将数据传递给父组件/ React UseState - Can't pass data to parent component / React UseState 子组件将 props 传递给父组件的 useState -&gt; 返回未定义(反应) - child component pass props to parent's useState -> returning undefined (react) React parent 无法更新映射的 JSX 列表中的子组件 - React parent couldn't update a child component in a mapped JSX list 如何在 React 中将数据从映射对象传递到其父组件? - How to pass data from mapped objects to its parent component in React? React hooks:动态映射的组件子组件和独立于父组件的状态 - React hooks: Dynamically mapped component children and state independent from parent React Hooks (Rendering Arrays) - 父组件持有映射的子组件的引用与父组件持有 state 的子组件 - React Hooks (Rendering Arrays) - Parent component holding a reference of children that are mapped vs Parent component holding the state of children React forwardRef - 在组件和父组件中访问 ref - React forwardRef - access ref within component, and in parent 功能组件中useEffect()中的useState() - useState() within useEffect() in a functional component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM