如何在React MDEditor中用数据库数据覆盖默认值实现编辑?
点击编辑按钮后填充MDEditor与标签输入框的实现方案
核心实现步骤
调整编辑数据状态的初始类型:当前
editBlogData初始化为数组,但单个编辑博客是对象结构,改为对象更贴合实际场景:const [editBlogData, setEditBlogData] = useState({});在编辑函数中同步状态到输入组件:获取数据库返回的博客数据后,直接更新
blogValue和tagValue,利用React的状态驱动渲染特性,让绑定的MDEditor和标签输入框自动加载编辑内容:const handleBlogEdit = (idx) => { console.log("this is the blog id::" + idx); const params = { id: idx }; const fetchData = async () => { try { const res = await axios.get(`${appUrl}/service/findblogtoedit`, { params }); const blogData = res.data.blogData; setEditBlogData(blogData); // 同步博客内容到MDEditor setBlogValue(blogData.blogdetails); // 同步标签到输入框 setTagValue(blogData.tags); } catch (e) { console.log(e); } }; fetchData(); };可选优化:区分新建/编辑状态:如果需要避免编辑时误触发新建逻辑,可以增加状态标记,在提交时调用对应接口:
const [isEditing, setIsEditing] = useState(false); const [currentEditId, setCurrentEditId] = useState(null); // 在handleBlogEdit中标记编辑状态 const handleBlogEdit = (idx) => { // ... 原有数据获取代码 setIsEditing(true); setCurrentEditId(idx); }; // 修改提交函数适配编辑场景 const onSubmit = () => { const email = localStorage.getItem('loginEmail'); const fetchData = async () => { try { let res; if (isEditing) { // 调用更新接口 res = await axios.put(`${appUrl}/service/updateblog`, { id: currentEditId, email, blogValue, tagValue }); setHelperText("Successfully updated the blog data !"); } else { // 原有创建逻辑 res = await axios.post(`${appUrl}/service/createblogs`, { email, blogValue, tagValue }); setHelperText("Successfully inserted the blog data !"); } if (res.data.success) { setBlogValue(""); setTagValue(""); setIsEditing(false); setCurrentEditId(null); window.location.reload(true); } } catch (e) { console.log(e); } }; fetchData(); };
内容的提问来源于stack exchange,提问作者soccerway
相关产品推荐
相关产品推荐

