繁体   English   中英

如何在reactjs中更新状态?

[英]How to update the state in reactjs?

最初我有一个CKeditor组件,从那里有一个状态变量editorContent

 <CKEditor id="currentCKEditor" activeClass="editor" key={this.state.editorContent} content={this.state.editorContent} events={{ "change": this.onChange, "instanceReady": this.ckeditorInstanceReady }} />

呈现组件时,editorContent来自templatestoreChange。 EditorContent状态具有以下数据

_templateStoreChange(type) {

    if (type == 'SingleTemplate') {
        let singletemplate = TemplateStore._getSingleTemplate() || {};
        console.log("single template response", singletemplate);
        this.setState({ editorContent: singletemplate.template.html });
    }
}

在这里调用templateStoreChange logSig之后,editorContent发生更改。 而不是editorContent状态得到更新这是以前的状态正在被删除并更改整个editorContent。

  logSig = () => {
   const signaturedata = this.signaturePad.toDataURL();

    let elem= '<img alt src=' + signaturedata + ' />';
    this.setState({
        openSignatureDialog: false,
        editorContent:elem
    })
    console.log("signaturedata", signaturedata);

}`enter code here`

我需要更新状态,而不是删除整个状态并将其更改为新状态。

您仅将elem变量分配给editorContent并且丢失了之前创建的全部内容。

解决方案是将elem变量连接到现有状态。

logSig = () => {
    const signaturedata = this.signaturePad.toDataURL();

    let elem = '<img alt src=' + signaturedata + ' />';
    this.setState({
        openSignatureDialog: false,
        editorContent: this.state.editorContent + elem
    })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM