如何更新由数组渲染的先前React组件的状态

huangapple go评论66阅读模式
英文:

How to update state for previous React component which rendered from array

问题

以下是您要翻译的内容:

我在点击添加组件按钮后向数组中添加了一个React组件并渲染该数组每个组件都通过将其作为prop传递来渲染计数hook

问题出在这里一旦组件添加到数组并渲染即使我通过按钮增加计数计数hook也会更新但从数组中渲染的组件不会更新当我再次点击添加组件按钮时新组件将以更新的hook渲染但以前的组件不会在增加时更新

# App.js
```jsx
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>
  )
}

<details>
<summary>英文:</summary>

I am adding a React component in Array with (add component) button click and rendering that array. Each component is rendering a count hook by giving it as a prop. 

Here&#39;s the problem comes, once component is added in array and rendered. Even if I increment the count with button, count hook is also updating, but component rendering from array is not updating. When I click on (add component) button again then that new component will render with updated hook. But previous components are not updating with increment.

# 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}>Add Component</button>
<button onClick={increment}>Increment</button>
{comp}
</>
)
}

export default App;


# Component.jsx

import React from 'react'

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



</details>


# 答案1
**得分**: 1

`useState()` hook实际上建议存储基本类型或简单对象。将组件存储在其中是一个很酷的想法,但从性能的角度来看,这对React来说确实是一个很大的负担。

更好的解决方案是使用基本类型的值,然后在渲染时将这些值传递给`map`。以下是一个很好的示例:

```javascript
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;
英文:

the useState() hook actually is recommending to store primitive types or simple objects. It is a cool idea to store components in it but performance-wise it is really a heavy lift on react side.

better solution is to use primitive type values and just pass the values to a map when rendering. Here is a good example:

import React, { useState } from &#39;react&#39;;
import Component from &#39;./Components/Component&#39;;

function App() {
  const [comp, setComp] = useState([]);
  const [count, setCount] = useState(0);

  const addComp = () =&gt; {
    setComp(prevState=&gt;[...prevState, count])
  }

  const increment = () =&gt; {
    setCount(prevState=&gt;prevState+1)
  }

  return (
    &lt;&gt;
      &lt;button onClick={addComp}&gt;Add Component&lt;/button&gt;
      &lt;button onClick={increment}&gt;Increment&lt;/button&gt;
      {comp.map((c,index) =&gt; &lt;Component key={index} count={c}&gt;&lt;/Component&gt;)}
    &lt;/&gt;
  )
}

# export default App;

答案2

得分: 0

以下是翻译好的部分:

这种方式存储组件并不理想。理想情况下,我们应该只将信息(props)存储在状态中,那样应该可以正常工作。

示例:
在你的情况下,我们可以这样做:

  const [comp, setComp] = useState(0);
  const [count, setCount] = useState(0);

  const addComp = () => {
    setComp(prevState => prevState + 1)
  }

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

  return (
    <>
      <button onClick={addComp}>添加组件</button>
      <button onClick={increment}>增加</button>
      {Array.from({length: comp}).map((_, i) => (
        <Component key={i} count={count}></Component>
      ))}
    </>
  )

希望这能帮助你理解代码。如果有任何问题,请随时提出。

英文:

It is not ideal to store components in a state the way you did. Ideally, we would just store the information(props) in the state and that should work.

Example:
In your case, we can do it this way

  const [comp, setComp] = useState(0);
  const [count, setCount] = useState(0);

  const addComp = ()=&gt;{
    setComp(prevState=&gt; prevState+1)
  }

  const increment = ()=&gt;{
    setCount(prevState=&gt;prevState+1)
  }

  return (
    &lt;&gt;
      &lt;button onClick={addComp}&gt;Add Component&lt;/button&gt;
      &lt;button onClick={increment}&gt;Increment&lt;/button&gt;
      {Array.from({length: comp}).map((_, i) =&gt; (
        &lt;Component key={i} count={count}&gt;&lt;/Component&gt;
      )}
    &lt;/&gt;
  )

huangapple
  • 本文由 发表于 2023年5月31日 23:32:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375150.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定