Javascript Can';t在draft.js中设置editorState(它看起来不可变,但没有错误)
我已经使用ConvertRow将内容保存到数据库中,我正试图将其加载回draft.js编辑器,以便用户能够重新编辑内容 js编辑器包含在一个基本组件中,当用户单击内容块上的“编辑”时会显示该组件。这一点很重要,因为模态(和编辑器)没有被重新实例化,它们只是被显示和隐藏 编辑器在(ES6)类构造函数中启动一次,只需使用:Javascript Can';t在draft.js中设置editorState(它看起来不可变,但没有错误),javascript,reactjs,draftjs,Javascript,Reactjs,Draftjs,我已经使用ConvertRow将内容保存到数据库中,我正试图将其加载回draft.js编辑器,以便用户能够重新编辑内容 js编辑器包含在一个基本组件中,当用户单击内容块上的“编辑”时会显示该组件。这一点很重要,因为模态(和编辑器)没有被重新实例化,它们只是被显示和隐藏 编辑器在(ES6)类构造函数中启动一次,只需使用: this.state = {editorState: EditorState.createEmpty()} 当用户单击“编辑”时,我从数据库加载原始内容,然后我尝试使用以下多种
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 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);
在我的项目中,我是这样做的
const blocks = convertFromRaw(props.rawBlocks);
editorState = EditorState.createWithContent(blocks, null);
好的,我已经知道问题出在哪里了 在尝试调用
setState()
之后,我立即将焦点设置到编辑器
i、 e.我在编辑器上调用
focus()
,在我尝试设置state之前,通过将focus()
调用移动到,一切都正常。显然,接受焦点对编辑状态有影响。好的,我已经发现了问题所在
我试图调用setState()
,然后立即将焦点设置为编辑器
i、 e.我在编辑器上调用
focus()
,在我尝试设置state之前,通过将focus()
调用移动到,一切都正常。显然,接受焦点对编辑状态有影响。谢谢@jiang YD我的问题似乎在这个。设置状态,它根本没有更新状态。谢谢@jiang YD我的问题似乎在这个。设置状态,它根本没有更新状态。