我試圖讓一個函數只在contentState本身發生變化時運行,而不僅僅是編輯器狀態。最好的性能方法來檢查contentState是否在DraftJS中更改,或者只是編輯器狀態
我現在的想法是將舊的contentState存儲爲字符串,並將其作爲字符串與新的contentState進行比較,但將狀態轉換爲字符串並進行比較似乎非常浪費。有沒有更好的辦法?
我試圖讓一個函數只在contentState本身發生變化時運行,而不僅僅是編輯器狀態。最好的性能方法來檢查contentState是否在DraftJS中更改,或者只是編輯器狀態
我現在的想法是將舊的contentState存儲爲字符串,並將其作爲字符串與新的contentState進行比較,但將狀態轉換爲字符串並進行比較似乎非常浪費。有沒有更好的辦法?
你可以簡單地比較你的old state
和你的new state
的值,你不必convert
它到string
。
編輯:這裏是一個概念,關於反應state
,你沒有關於large state object
擔心的最佳做法建議做這樣
常見的誤解:
state
是在large object
舉行。這只是對象引用其他一些對象。沒什麼大關係。
公平一點,但它似乎仍然浪費這個比較大的對象進行比較的每次點擊,按鍵等。我是否在推翻這個? 我知道這樣一件小事不會殺死性能,但它看起來很浪費。這是最浪費的方式嗎? – Slbox
當你沒有簡單的方法來用'新狀態'更新它們時,可以比較它們在你提到'大對象'時的情況。 –
請注意,由於它們是不可變的對象,因此比較很快就可以完成。它比較的是身份,而不是內容。也就是說,'this.state.editorState.getCurrentContent()=== newEditorState.getCurrentContent()' –
我已經使用另一種方法來檢查編輯器內容是否已經改變。
基本上我利用一個NPM模塊deep-equal的比較原始contentState對象(即contentState使用convertToRaw函數轉換爲簡單的JS對象)。 在您的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.');
}
這比僅僅檢查最高級的答案所建議的引用等式要昂貴得多。 –
這是不是從費薩爾穆什塔克的回答如此不同,但包括一些改進。在組件的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)
}
如果您共享進行比較的代碼,我們可以更詳細幫助,如果我的回答不會幫助你多少 –