我有一个位于父组件循环内的子组件。当其中一个子组件正在更新父组件的状态时,它会重新渲染所有子组件,因为它是循环的。如何避免每次迭代重新渲染。
function Parent() {
  const [selectedChild, setSelectedChild] = useState([]);
  const onChangeHandle = (event, id) => {
    const checked = event.target.checked;
      let updatedArray = [...selectedChild];
      if(checked){
         if(!selectedChild.includes(id)){
            updatedArray.push(id); 
         }
      }
      else{
         var index = updatedArray.indexOf(id)
         if (index !== -1) {
            updatedArray.splice(index, 1);
         }
      }
      setSelectedChild(updatedArray);
  }
  const dummy = (id) => {
    return selectedChild.includes(id);
  }
  return (
    <div>
    <table>
    <tbody>
      {[1,2,3].map((value, index) => {
      return (
        <Child 
        key={index} 
        index={index} 
        value={value} 
        handle={onChangeHandle}
        isSelected={dummy}
        />
      )
      })}
    </tbody>
    </table>
    <div>
      {selectedChild}
    </div>
  </div>)
}
function Child({index, value, handle, isSelected }) {
  console.log('rendering')
 return (
 <tr>
    <td>
      <input 
      type="checkbox" 
      checked={isSelected(index)}
      onChange={(event) => handle(event, index)}/>
    </td>
    <td>hello {index} {value}</td>
 </tr>
 )
}
export default function App() {
  return (
    <div className="App">
      <Parent />
    </div>
  );
}
当前行为:
在上面的代码中,当我单击子组件之一中的复选框时,它正在更新父组件状态(selectedChild)。所以循环正在执行并且所有子项(所有表行)都在重新呈现。
预期行为: 只有该特定行必须重新渲染