简体   繁体   中英

React / ES6 - Efficiently update property of an object in an array

I am looking for the most efficient way to update a property of an object in an array using modern JavaScript. I am currently doing the following but it is way too slow so I'm looking for an approach that will speed things up. Also, to put this in context, this code is used in a Redux Saga in a react app and is called on every keystroke * a user makes when writing code in an editor.

*Ok not EVERY keystroke. I do have debounce and throttling implemented I just wanted to focus on the update but I appreciate everyone catching this :)

function* updateCode({ payload: { code, selectedFile } }) {
  try {
    const tempFiles = stateFiles.filter(file => file.id !== selectedFile.id);

    const updatedFile = {
      ...selectedFile,
      content: code,
    };

    const newFiles = [...tempFiles, updatedFile];
  }
  catch () {}
}

the above works but is too slow.

I have also tried using splice but I get Invariant Violation: A state mutation

const index = stateFiles.findIndex(file => file.id === selectedFile.id);
const newFiles = Array.from(stateFiles.splice(index, 1, { ...selectedFile, content: code }));

You can use Array.prototype.map in order to construct your new array:

const newFiles = stateFiles.map(file => {
  if (file.id !== selectedFile.id) {
    return file;
  }
  return {
    ...selectedFile,
    content: code,
  };
});

Also, please consider using debouncing in order not to run your code on every keystroke.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM