When I click the "Add Component" button, I add a React component to the array and render the array. Each component is rendered by passing it as a property to the count hook.
The problem is that once the component is added to the array and rendered out, even if I increment the count via the button, the count hook updates, but the component rendered from the array does not update. When I click the "Add Component" button again, the new component will be rendered with the updated hook. But previous components will not be updated as they are added.
import React, { useState } from 'react'; import Component from './Components/Component'; function App() { const [comp, setComp] = useState([]); const [count, setCount] = useState(0); const addComp = ()=>{ setComp(prevState=>{ return([...prevState,<Component key={comp.length} count={count}></Component>]) }) } const increment = ()=>{ setCount(prevState=>prevState+1) } return ( <> <button onClick={addComp}>添加组件</button> <button onClick={increment}>增加</button> {comp} </> ) } # export default App;
import React from 'react' export default function Component(props) { return ( <div>{props.count}</div> ) }
useState() hook actually recommends storing primitive types or simple objects. It's a cool idea to store components in it, but it's really a heavy burden on React from a performance perspective.
A better solution is to use primitive type values and pass these values to the map when rendering. Here's a good example: