【发布时间】:2016-08-02 00:53:33
【问题描述】:
我已使用 convertToRaw 将内容保存到数据库中,我正在尝试将其加载回 draft.js 编辑器,以使用户能够重新编辑内容。
draft.js 编辑器包含在基于react-modal 的组件中,当用户在内容上单击“编辑”时会显示该组件。这很重要,因为模态(和编辑器)没有重新实例化,它们只是显示和隐藏。
编辑器在 (ES6) 类构造函数中启动一次,只需使用:
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}) 仅针对编辑器组件失败。
我已经通过设置测试状态属性并成功更新它来测试它,而editorState保持不变。
为了全面测试这一点,在我的构造函数中,我使用测试值初始化了状态:
this.state = {
editorState:EditorState.createWithContent(ContentState.createFromText('Hello')),
testVal: 'Test Val 1'
}
然后我编写了一些测试代码来展示 setState 如何适用于我的测试值,但不适用于 Draft.js 编辑器状态:
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 没有更新?
【问题讨论】:
标签: javascript reactjs draftjs