【问题标题】:Draft-js do not save databaseDraft-js 不保存数据库
【发布时间】:2020-01-29 23:05:55
【问题描述】:

我无法将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;

【问题讨论】:

  • 抱歉,您遇到的具体问题是什么?保存了超过 1 个标头..?
  • 是的,我有两个带有标题和描述的字段。写入数据库只是标题

标签: javascript reactjs axios draftjs


【解决方案1】:

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

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() 请求时将其发送到您的服务器端。

【讨论】:

    猜你喜欢
    • 2017-06-22
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    相关资源
    最近更新 更多