Method to update the state of the previous React component rendered by an array
P粉014218124
P粉014218124 2023-09-08 21:35:51
0
1
576

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.

App.js

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;

Component.jsx

import React from 'react'

export default function Component(props) {
  return (
    <div>{props.count}</div>
  )
}

P粉014218124
P粉014218124

reply all(1)
P粉841870942

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:

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=>[...prevState, count])
  }

  const increment = () => {
    setCount(prevState=>prevState+1)
  }

  return (
    <>
      <button onClick={addComp}>Add Component</button>
      <button onClick={increment}>Increment</button>
      {comp.map((c,index) => <Component key={index} count={c}></Component>)}
    </>
  )
}

# export default App;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template