![](/img/trans.png)
[英]How to use redux store to properly update EditorState in Draft.js
[英]Can't set editorState in draft.js (it appears immutable but with no error)
我已經使用convertToRaw將內容保存到數據庫中,試圖將其重新加載到draft.js編輯器中,以使用戶可以重新編輯內容。
draft.js編輯器包含在基於react-modal的組件中,當用戶單擊內容上的“ edit”時將顯示該組件。 這很重要,因為模式(和編輯器)沒有重新實例化,它們只是顯示和隱藏。
在(ES6)類構造函數中,只需使用以下命令即可啟動一次Editor:
this.state = {editorState: EditorState.createEmpty()}
當用戶單擊“編輯”時,我將從數據庫中加載原始內容,然后嘗試使用以下幾種變體將原始內容加載到編輯器中:
const contentState = convertFromRaw(rawContent)
const newEditorState = EditorState.push(this.state.editorState, contentState);
this.setState({editorState: newEditorState})
但是,盡管newEditorState顯然包含正確的內容,但this.setState({editorState: newEditorState})
似乎對組件(或編輯器)的狀態完全沒有影響。
我應該如何設置編輯器的新狀態? 謝謝!
更新在進一步的調查中,顯然只是this.setState({editorState: newEditorState})
僅針對Editor組件而失敗。
我已經通過設置測試狀態屬性並成功更新它進行了測試,而editorState保持不變。
為了進行全面測試,在我的構造函數中,我使用以下值初始化了測試值:
this.state = {
editorState:EditorState.createWithContent(ContentState.createFromText('Hello')),
testVal: 'Test Val 1'
}
然后,我編寫了一些測試代碼,以顯示setState如何用於我的測試值,而不適用於draft.js editorState:
const newEditorState = EditorState.createWithContent(ContentState.createFromText('Goodbye'))
console.log('Before setState')
console.log('newEditorState: ' + newEditorState.getCurrentContent().getPlainText());
console.log('editorState: ' + this.state.editorState.getCurrentContent().getPlainText());
console.log('testVal: ' + this.state.testVal);
this.setState({editorState: newEditorState, testVal: 'Test Val 2'}, function(){
console.log('After setState')
console.log('editorState: ' + this.state.editorState.getCurrentContent().getPlainText());
console.log('testVal: ' + this.state.testVal);
});
控制台輸出如下所示:
Before setState
newEditorState: Goodbye
editorState: Hello
testVal: Test Val 1
After setState
editorState: Hello
testVal: Test Val 2
我看不到為什么testVal時未更新draft.js editorState?
我在我的項目中做到了以下幾點
const blocks = convertFromRaw(props.rawBlocks);
editorState = EditorState.createWithContent(blocks, null);
好的,我發現了問題所在。
在嘗試調用setState()
之后,我立即將焦點設置到Editor上。
即我在編輯器上調用focus()
,方法是在我嘗試設置State 之前將focus()
調用移至,這一切都奏效了。 顯然接受焦點會對editorState產生影響。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.