使用useState钩子有效地更新数组中的对象

spi*_*ech 8 reactjs react-hooks

我有一个React组件,可以渲染一个相当大的输入列表(超过100个项目)。它可以在我的计算机上正常显示,但是手机上的输入延迟明显。React DevTools显示,每次按键时都会重新渲染整个父对象。

有没有更有效的方法来解决这个问题?

https://codepen.io/anon/pen/YMvoyy?editors=0011

function MyInput({obj, onChange}) {
  return (
    <div>
      <label>
        {obj.label}
        <input type="text" value={obj.value} onChange={onChange} />
      </label>
    </div>
  );
}

// Passed in from a parent component
const startingObjects = 
  new Array(100).fill(null).map((_, i) => ({label: i, value: 'value'}));

function App() {
  const [objs, setObjects] = React.useState(startingObjects);
  function handleChange(obj) {
    return (event) => setObjects(objs.map((o) => {
      if (o === obj) return {...obj, value: event.target.value}
      return o;
    }));
  }
  return (
    <div>
      {objs.map((obj) => <MyInput obj={obj} onChange={handleChange(obj)} />)}  
    </div>
  );
}


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Run Code Online (Sandbox Code Playgroud)

use*_*824 11

该问题与以下方面有关:

function handleChange(obj) {
  return (event) => setObjects(objs.map((o) => {
    if (o === obj) return {...obj, value: event.target.value}
    return o;
  }));
}
Run Code Online (Sandbox Code Playgroud)

在此,您将更新objs阵列。显然这很好,但是React不知道发生了什么变化,因此在所有子项上触发了Render。

如果您的功能组件使用相同的道具呈现相同的结果,则可以将其包装在对React.memo的调用中以提高性能。

https://reactjs.org/docs/react-api.html#reactmemo

const MyInput = React.memo(({obj, onChange}) => {
    console.log(`Rerendered: ${obj.label}`);
    return <div style={{display: 'flex'}}>
        <label>{obj.label}</label>
        <input type="text" value={obj.value} onChange={onChange} />
    </div>;
}, (prevProps, nextProps) => prevProps.obj.label === nextProps.obj.label && prevProps.obj.value === nextProps.obj.value);
Run Code Online (Sandbox Code Playgroud)

但是,React.Memo仅在尝试确定是否应渲染时才进行浅表比较,因此我们可以将自定义比较函数作为第二个参数传递。

(prevProps, nextProps) => prevProps.obj.label === nextProps.obj.label && prevProps.obj.value === nextProps.obj.value);
Run Code Online (Sandbox Code Playgroud)

基本上来说,如果objprop 上的标签和值与先前objprop 上的先前属性相同,请不要重新渲染。

最后,setObjects就像setState一样,它也是异步的,不会立即反映和更新。因此,为避免objs出现不正确的风险并使用较旧的值,可以将其更改为如下所示的回调:

function handleChange(obj) {
  return (event) => {
    const value = event.target.value;
    setObjects(prevObjs => (prevObjs.map((o) => {
      if (o === obj) return {...obj, value }
      return o;
    })))
  };
}
Run Code Online (Sandbox Code Playgroud)

https://codepen.io/anon/pen/QPBLwy?editors=0011拥有所有这些内容以及console.logs,显示是否重新渲染了某些内容。


有没有更有效的方法来解决这个问题?

您将所有值存储在数组中,这意味着您不知道需要更新哪个元素,而无需遍历整个数组,就比较对象是否匹配。

如果从对象开始:

const startingObjects = 
  new Array(100).fill(null).reduce((objects, _, index) => ({...objects, [index]: {value: 'value', label: index}}), {})
Run Code Online (Sandbox Code Playgroud)

进行一些修改后,您的handle函数将变为

function handleChange(obj, index) {
  return (event) => {
    const value = event.target.value;
    setObjects(prevObjs => ({...prevObjs, [index]: {...obj, value}}));
  }
}
Run Code Online (Sandbox Code Playgroud)

例如https://codepen.io/anon/pen/LvBPEB?editors=0011