【问题标题】:Can't set editorState in draft.js (it appears immutable but with no error)无法在 draft.js 中设置 editorState(它看起来不可变但没有错误)
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 感谢@jiang-YD 我的问题似乎出在 this.setState 中,它似乎根本没有更新状态。
    【解决方案2】:

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

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

    即我在编辑器上调用focus(),通过将focus() 调用移动到之前我尝试setState,这一切都奏效了。明确接受焦点对 editorState 有影响。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多