javascript - 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;
解决方案
根据您提供给我的完整代码,我意识到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()
请求时将其发送到您的服务器端。
推荐阅读
- sed - Linux sed 去除两种模式
- r - 计算 R 中参与者产生的平均单词
- angular - 这应该进入什么文件?数据路径“”应具有必需的属性“名称”
- python - 涉及熊猫中两列的聚合
- c - 虚拟内存混乱
- c# - IOS 14 请求限制照片访问
- scala - 在scala-spark中如何减少多个案例
- c++ - 删除的函数'virtual Classname::~Classname()'覆盖未删除的函数VIRTUAL DESTRUCTOR
- python - Cloud Build 服务帐号无权访问 storage.objects.get
- python - Pandas 按唯一 ID 和每个唯一 ID 的不同日期分组