如何避免在父组件状态更新时重新渲染循环中的所有子组件

Sug*_*Raj 5 javascript reactjs react-hooks react-usememo

我有一个子组件,它位于父组件的循环内。当子组件之一更新父组件的状态时,它会重新渲染所有子组件,因为它是循环的。我怎样才能避免每次迭代的重新渲染。


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>
  );
}
Run Code Online (Sandbox Code Playgroud)

当前行为: 在上面的代码中,当我单击子组件之一中的复选框时,它正在更新父组件状态(selectedChild)。因此循环正在执行,所有子项(所有表行)都在重新渲染。

预期行为: 只有该特定行需要重新渲染

演示: https: //codesandbox.io/s/newpro-0pezc

lt1*_*lt1 0

您可以在 Child 的定义中实现 shouldComponentUpdate (文档:https: //reactjs.org/docs/react-component.html#shouldcomponentupdate ),以更好地控制它何时重新渲染。但这仅适用于遇到性能问题的情况 - 通常您不必担心它,并且让它们全部重新渲染是标准做法。