Draft.js-createWithContent或convertFromRaw引发错误

问题描述

我正在尝试在要创建的Blog应用程序中使用Draft.js。 将数据保存到数据库并将其恢复时,一切似乎都很好,只是我似乎无法使createWithContent工作。为了清楚起见,我将向您展示我的大部分代码,如果可能看起来太多,表示歉意。

这是我设置项目的方式:

这是发布模型

const postSchema = new mongoose.Schema(
  {
    title: {
      type: String,required: true,},image: { type: String,required: true },images: [String],paragraph: { type: String,{ timestamps: true }
);

const Post = mongoose.model('Post',postSchema);

export default Post;

这是路由器,用于获取修改帖子:

postRouter.get(
  '/:id',expressAsyncHandler(async (req,res) => {
    const post = await Post.findOne({ _id: req.params.id });
    if (post) {
      res.send(post);
    } else {
      res.status(404).send({ message: 'Post Not Found.' });
    }
  })
); 
postRouter.put(
  '/:id',isAuth,isAdmin,res) => {
    const postId = req.params.id;
    const post = await Post.findById(postId);
    if (post) {
      post.title = req.body.title;
      post.image = req.body.image;
      post.images = req.body.images;
      post.paragraph = req.body.paragraph;

      const updatedPost = await post.save();
      if (updatedPost) {
        return res
          .status(200)
          .send({ message: 'Post Updated',data: updatedPost });
      }
    }
    return res.status(500).send({ message: ' Error in Updating Post.' });
  })
);

这些是 Redux操作,用于获取帖子的详细信息并进行更新:

export const updatePost = (post) => async (dispatch,getState) => {
  try {
    dispatch({ type: POST_UPDATE_REQUEST,payload: post });

    const {
      userSignin: {
        userInfo: { token },} = getState();

    const { data } = await Axios.put(`/api/posts/${post._id}`,post,{
      headers: {
        Authorization: `Bearer ${token}`,});
    dispatch({ type: POST_UPDATE_SUCCESS,payload: data });
  } catch (error) {
    dispatch({
      type: POST_UPDATE_FAIL,payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,});
  }
};

export const detailsPost = (postId) => async (dispatch) => {
  try {
    dispatch({ type: POST_DETAILS_REQUEST,payload: postId });
    const { data } = await Axios.get(`/api/posts/${postId}`);
    dispatch({ type: POST_DETAILS_SUCCESS,payload: data });
  } catch (error) {
    dispatch({
      type: POST_DETAILS_FAIL,});
  }
};

和相应的减速器

export const postDetailsReducer = (
  state = { loading: true,post: { comments: [] } },action
) => {
  switch (action.type) {
    case POST_DETAILS_REQUEST:
      return { ...state,loading: true };
    case POST_DETAILS_SUCCESS:
      return { loading: false,post: action.payload };
    case POST_DETAILS_FAIL:
      return { ...state,loading: false,error: action.payload };
    case POST_DETAILS_RESET:
      return { post: { comments: [] } };
    default:
      return state;
  }
};


export const postUpdateReducer = (state = { post: {} },action) => {
  switch (action.type) {
    case POST_UPDATE_REQUEST:
      return { loading: true };
    case POST_UPDATE_SUCCESS:
      return { loading: false,success: true,post: action.payload };
    case POST_UPDATE_FAIL:
      return { loading: false,error: action.payload };
    case POST_UPDATE_RESET:
      return { post: {} };
    default:
      return state;
  }
};

这些是 Redux商店中的化简:

userDetails: userDetailsReducer,userUpdate: userUpdateReducer,

最后,我在屏幕中尝试更新帖子。在这里,我设置了以下内容

  const postId = props.match.params.id;
  const dispatch = usedispatch();
  const [id,setId] = useState('');
  const [title,setTitle] = useState('');
  const [image,setimage] = useState('');
  const [images,setimages] = useState([]);
  const [uploading,setUploading] = useState(false);
  
  const postDetails = useSelector((state) => state.postDetails);
  const { loading,error } = postDetails; 
  const postUpdate = useSelector((state) => state.postUpdate);
  const {
    error: errorUpdate,loading: loadingUpdate,success: successUpdate,} = postUpdate;

const editorContent = EditorState.createEmpty();

const [editorState,setEditorState] = useState({ editorState: editorContent });

const handleEditorChange = (editorState) => { setEditorState({ editorState }) }

然后

useEffect(() => {
    if (successUpdate) {
      dispatch({ type: POST_UPDATE_RESET });
      props.history.push(`/postlist`);
    }
    if (!post.title) {
      dispatch(detailsPost(postId));
    } else {
      setId(post._id);
      setTitle(post.title);
      setimage(post.image);
      setimages(post.images);
    }

    return () => {
      //
    };
  },[post,successUpdate,dispatch,props.history,postId]);

在这里,通过 submitHandler我调度了Redux操作,该操作将数据发送到数据库

const submitHandler = (e) => {
    e.preventDefault();
    dispatch(
      updatePost({
        _id: id,title,image,images,paragraph: JSON.stringify(convertToRaw(editorState.editorState.getCurrentContent()))
      })
    );
  };

和我的编辑器位于以下底部

<return (
<div>
  <form className="form" onSubmit={submitHandler}>

    <div>
      <h1>Edit Post {id}</h1>
    </div>

    {loadingUpdate && <LoadingBox />}
    {errorUpdate && <MessageBox variant="error">{errorUpdate}</MessageBox>}
    {loading && <LoadingBox />}
    {error && <MessageBox variant="error">{error}</MessageBox>}
    {post.title && (
      <>
        <div>
          <label htmlFor="name">Title</label>
          <input
            id="name"
            type="text"
            placeholder="Enter title"
            value={title}  
            onChange={(e) => setTitle(e.target.value)}
          />
        </div>
      
        <div>
          <label htmlFor="image">Image Url</label>
          <input
            id="image"
            type="text"
            placeholder="Enter image url"
            value={image}
            onChange={(e) => setimage(e.target.value)}
          />
        </div>
        
        <div>
          <div />
          <div>
            <button
              onClick={() => props.history.push('/postlist')}
              type="button"
            >
              Back
            </button>{' '}
            <button className="primary" type="submit">
              Update
            </button>
          </div>
        </div>

        <div>
          <label htmlFor="paragraph">Paragraph</label>
          <Editor
            editorState={editorState.editorState}
            onEditorStateChange={handleEditorChange}
          />
        </div>
        
      </>
    )}
  </form>
</div>
)

现在,该段落(以及我未使用文本编辑器的其他数据)已成功保存在数据库中,并且如下所示(在JSON.stringify(convertToRaw()之后):

{"blocks":[{"key":"20f7q","text":" Hello World","type":"unstyled","depth":0,"inlinestyleRanges":[{"offset":1,"length":3,"style":"bgcolor-yellow"}],"entityRanges":[],"data":{}}],"entityMap":{}}

我想要的虽然不是Empty编辑器,但我希望成为一名编辑现有段落的安倍晋三。因此,我将editorContent更改为以下内容

const editorContent = post ?
    EditorState.createWithContent(convertFromraw(JSON.parse(post.paragraph))) :
    EditorState.createEmpty();

这一切对我来说似乎很好,我什至还从Redux商店获得console.logged post ,以检查我是否确实有数据以及段落包括在内。 因此,我不明白以下错误是从哪里来的:

enter image description here

引发了跨域错误。 React无法访问 开发中的实际错误对象。

我什至在代码添加了以下几行来处理跨源代码

app.use((req,res,next) => {
  res.setHeader('Access-Control-Allow-Origin','*'); 
  res.setHeader('Access-Control-Allow-Headers','Origin,X-Requested-With,Content,Accept,Content-Type,Authorization'); 
  res.setHeader('Access-Control-Allow-Methods','GET,POST,PUT,DELETE,PATCH,OPTIONS'); 
  next();
});

回顾,似乎我能够创建一个空的编辑器并将数据发送到数据库,但是即使我尝试使用的数据却试图创建createWithContent时也遇到错误确实存在! 我真的不知道该尝试什么,因为一切对我来说都很好,因此任何想法或建议都将受到高度赞赏。 非常感谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)