我正在尝试仅在contentState本身发生更改时才运行函数,而不仅仅是editorState。
我现在的想法是将旧的contentState存储为字符串,并将其作为字符串与新的contentState进行比较,但将状态转换为字符串并进行比较似乎非常浪费。还有更好的方法吗?
答案 0 :(得分:3)
您只需将old state
的值与您不必拥有的new state
的值convert
与string
进行比较。
编辑:这是一个关于反应state
的概念,您不必担心large state object
,因为最佳做法建议这样做
常见的误解:
state
保存在large object
中。它只是引用一些其他对象的对象。没什么大不了的。
答案 1 :(得分:0)
我使用了另一种方法来检查编辑器内容是否已更改。
基本上我正在使用npm模块deep-equal来比较原始contentState对象(即使用convertToRaw函数转换为简单JS对象的contentState)。 在onChange处理程序中,比较旧的和原始的contentState对象。
注意:深度相等模块的比较比在try / catch中包装节点的assert.deepEqual()快5倍。
这是onChange处理程序代码:
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.');
}
答案 2 :(得分:0)
这与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)
}