首页 > 解决方案 > Draft-js 不保存数据库

问题描述

我无法保存description为组件状态的一部分。我只能保存标题。如何将标题和描述保存到数据库?

const BlogCreate = ({ history }) => {
const [blogCreate, setBlogCreate] = useState({
    title: "",
    description: ""
});
const [editorState, setEditorState] = useState(
    EditorState.createEmpty(),
);
const handleChange = ({ currentTarget }) => {
    const { name, value } = currentTarget;
    setBlogCreate({...blogCreate, [name]: value});
};
const onEditorStateChange = editorState => {
    setEditorState(editorState);
};
const handleSubmit = async event => {
    event.preventDefault();
    const data = draftToHtml(convertToRaw(editorState.getCurrentContent())); 
    try {
        await blogAPI.create(blogCreate, data);
    } catch (error) {
         console.log(error)
        }
    }
    console.log(data);
}
return(
      <Field type="text" name="title" error={errors.title} value={blogCreate.title} 
               onChange={handleChange} 
             />
      <Editor name="description" editorState={editorState} onEditorStateChange={editorState => onEditorStateChange(editorState)}
             />
      <button type="submit">Save</button>    
   );
}
export default BlogCreate;

标签: javascriptreactjsaxiosdraftjs

解决方案


根据您提供给我的完整代码,我意识到blogCreate只要组件发生更改,您就没有正确更新状态Editor

onEditorStateChange()应该更新blogCreate状态,此外,还需要changeValue()返回结果value

const changeValue = editorState => {
  const value = ....

  return value;
};

const onEditorStateChange = editorState => {
  const description = changeValue(editorState);
  setBlogCreate({
     ...blogCreate,
     description,
  });
  setEditorState(editorState);
};

这样,description将正确更新您的状态,并在您发出blogAPI.create()请求时将其发送到您的服务器端。


推荐阅读