Draft-jsJSON到EditorState不更新

Draft-js JSON to EditorState does not update

所以,我用 Draft-js 创建了博客 post。当用户创建一个post时,数据被转换为字符串并发送到服务器进行保存。我这样转换 draft-js EditorStateJSON.stringify(convertToRaw(editorState.getCurrentContent())).

现在,我想添加一个编辑 post 功能。为此,我从服务器获取字符串数据(格式与上述完全相同),然后尝试从中创建一个 editorState,如下所示:

let data = convertFromRaw(res.data['postContent'])
setEditorState(EditorState.createWithContent(data)) 

这似乎有效,因为我 运行 console.log(convertToRaw(editorState.getCurrentContent())) 我可以看到服务器数据在 editorState 中。但是,编辑器内部没有显示任何内容。我的问题:如何在编辑器中向用户显示数据并使其可编辑?就像这样,用户可以看到 post 并修改其中的一部分。 这是我得到的屏幕截图(如您所见,标题在那里,但当它应该说“测试数据!”时,编辑器是空的):

这是我的完整代码:

import React, {useEffect, useState} from 'react'
import { EditorState, convertToRaw, convertFromRaw } from 'draft-js'
import { useLocation } from 'react-router-dom';
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import './css/CreateBlog.css'
import ApiClient from '../util/ApiClient';


// submit the blog post
const submitPage = async (data, postTitle, setPosted, setPostFailed) => {
  const content = JSON.stringify(convertToRaw(data));
  ApiClient.post("/blog/handle-blog", {"postTitle": postTitle,"postContent": content})
  .then((res) => {
    console.log(res)
    // there was no error
    if(res.status === 201) {
      setPosted("Your blog has been posted.")
      setPostFailed(false)
    } else {
      setPosted("There was an error.")
      setPostFailed(true)
    }
  })
}


// if this is an edit 
const getPostData = async (postID, setEditorState, setPostTitle) => {
  const res = await ApiClient.get(`/blog/get-blog/${postID}`)
  // set the title and data 
  setPostTitle(res.data['postTitle'])
  setEditorState(EditorState.createWithContent(convertFromRaw(res.data['postContent'])))  // set the editorState data
}

export default function CreateBlogpost() {
  const location = useLocation();
  const postID = location.state?.id;  // get the ID if there is one

  const [editorState, setEditorState] = useState(null);
  const [postTitle, setPostTitle] = useState("");
  const [posted, setPosted] = useState(""); // the error/success message 
  const [postFailed, setPostFailed] = useState(false); // has the blog successfully been posted?

  // handle the post button click
  const handleSubmit = async (e) => {
    e.preventDefault();
    // check the post contains data
    if(editorState === EditorState.createEmpty() || postTitle == "") { 
      setPosted("Please add some content to your post.")
      setPostFailed(true)
      return;
    }
    const data = editorState.getCurrentContent()
    await submitPage(data, postTitle, setPosted, setPostFailed);
  }
  
  useEffect(() => {
    // if the state has an ID, then you're editing a post
    if(postID) {
      getPostData(postID, setEditorState, setPostTitle)
    }
  }, [])

  return(
    <div className="create-blog">
      <div className="create-blog-text m-2 mb-3">
        <h1>{postID ? "Edit" : "Create"} a blog post</h1>
      </div>
      <div className="d-flex">
        <h3 className="m-2">Title: </h3>
        <input value={postTitle} type="text" id="fname" className="m-2" onChange={e=>setPostTitle(e.target.value)} />
        <p className="m-2">Please note: if you want to upload a photo, upload it to an image sharing site like imgur and then link the image.</p>
      </div>
      <div className="editor-container mb-3 ml-2 mr-2" 
      style={{ border: "1px solid black", minHeight: "6em", cursor: "text" }}
      >
        <Editor value={editorState} onEditorStateChange={setEditorState} />
      </div>
      <button className="button-3 m-2" onClick={(e) => handleSubmit(e)}>
        {postID ? "Edit" : // if there is a postID, then you are editing the post
        "Post" }
      </button>
      {/* <button className="button-3 m-2" onClick={(e) => handleSubmit(e)}>Save as draft</button> */}
      <h4 style={{ color: postFailed ? 'red' : 'green'}}>{posted}</h4>
    </div>
  )
}

这是 sandbox 中的工作版本。我评论了 useLocationApiClient 调用,所以也许这些是罪魁祸首。另外你的 res.data['postContent'] 看起来像 JSON。如果是这样,那么您需要 JSON.parse(res.data['postContent']).

改变

<Editor
    value={editorState}
    onEditorStateChange={setEditorState}
/>

<Editor
    editorState={editorState}
    onEditorStateChange={setEditorState}
/>