The best performance way is to check if the contentState has changed in DraftJS, or just editorState

I try to run a function only when the content itself has changed, not just editorState.

My idea right now was to save the old content as a string and compare it with the new content as a string, but it seems terribly wasteful to convert states to strings and compare them. Is there a better way?

+4
source share
3 answers

you can simply compare your value old stateand your value new state, which you do not need convertso that it string.

EDIT: state, large state object, .

: state large object. . .

+3

Faisal Mushtaq, . constructor:

// keep track of the last state
let lastContentState = this.state.editorState.getCurrentContent()

this.onChange = editorState => {
  this.setState({ editorState })

  // push your handling code onto the call stack with a setTimeout
  // so that it doesn't block handling new inputs to the editor
  setTimeout(() => {

    // first-time focus or blur, no change to content
    if (!editorState.getLastChangeType()) return

    const currentContentState = editorState.getCurrentContent()

    // ES6 to compare, could use Immutable.is() instead
    const toHandle = !Object.is(lastContentState, currentContentState)

    if (toHandle) {
      // your handler function, eg passed in as a prop
      this.props.handleChange(currentContent)

      // current content becomes last content
      lastContentState = currentContentState
    }

  }, 0)
}
0

, .

npm deep-equal contentState (.. contentState JS convertToRaw). onChange contentState.

Note. Comparison using a module with a deep value is about 5 times faster than wrapping node assert.deepEqual () in try / catch.

Here is the onChange handler code:

const deepEqual = require('deep-equal');

this.onChange = (editorState) => {

    let oldContent = convertToRaw(this.state.editorState.getCurrentContent());
    let newContent = convertToRaw(editorState.getCurrentContent());

    let sameContent = deepEqual(oldContent, newContent);

    this.setState({editorState});

    if (sameContent === false)
      console.log('Content has changed.');
}
-1
source

Source: https://habr.com/ru/post/1652696/


All Articles