可以't在draft.js中设置editorState(它看起来是不可变的,但没有错误)

Can't set editorState in draft.js (it appears immutable but with no error)

本文关键字:不可变 看起来 有错误 editorState draft 设置 js 可以      更新时间:2023-09-26

我已经使用convertToRaw将内容保存到数据库中,我正试图将其加载回draft.js编辑器中,以使用户能够重新编辑内容。

draft.js编辑器包含在一个基于react模态的组件中,当用户单击内容上的"编辑"时,该组件就会显示出来。这一点很重要,因为模态(和编辑器)没有被重新实例化,它们只是被显示和隐藏。

编辑器在(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编辑器工作的State:

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

我不明白为什么draft.js editorState没有更新,而testVal是?

我在我的项目中使用了以下内容

const blocks = convertFromRaw(props.rawBlocks);
editorState = EditorState.createWithContent(blocks, null);

好的,我已经找到问题所在了。

在尝试调用setState()之后,我立即将焦点设置为编辑器。

即,我在编辑器上调用focus(),通过在之前将focus()调用移动到,我尝试设置State,一切都成功了。明确接受焦点对编辑国有影响。

相关文章: