添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams state belongs to an instance of a component. If you need this state for every item the component renders individually, you need to keep an object in the state where every item has a key and the corresponding value in that object. trixn Dec 16, 2021 at 9:14 Move the isExpanded state to the body of the function component and convert it to hold the value for each element of items you are mapping. Or abstract whatever it is that you are mapping into a React component so the hook usage is valid. Drew Reese Dec 16, 2021 at 9:18

In your case i would suggest creating a new component for the item.

{ items.map((item) => <Item key={} />) } const Item = () => { const [isExpanded, setIsExpanded] = useState(false) return ( // ...

option 2

const [expandedIds, setExpandedIds] = useState([]) {items.map((item) => { const expanded = checkIsExpended(item) return ( // ... @ytrewq Yes, but every Item component would have the call to useState unconditionally at the top. So it would solve the problem but the state would be local to the item. If you need it in the parent you would have to go with an object that stores the expanded state for each individual item. trixn Dec 16, 2021 at 9:28

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question . Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers .