You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中如何将MDEditor输入数据转为字符串并完整提交?

解决方案

问题根源

你现在的代码在输入每一个字符时都会触发onChange并立刻发起请求,而React的setValue是异步更新的,这不仅会导致频繁的无效请求,还可能因为状态没来得及同步,提交的不是最新的完整内容。另外fetchData函数里的参数定义也有点混乱,容易导致变量覆盖问题。

修正步骤

1. 拆分提交逻辑(推荐做法)

不要在输入时实时提交,单独做一个提交按钮,点击时再发送请求,这样能确保拿到的是最终完整的输入内容:

import MDEditor from '@uiw/react-md-editor';
import axios from 'axios';

const YourComponent = () => {
  const [value, setValue] = React.useState("**Create a new blog**");

  // 只负责更新编辑器内容的状态
  const handleChange = (newValue) => {
    setValue(newValue);
  };

  // 单独的提交函数,点击按钮时触发
  const handleSubmit = async () => {
    try {
      const res = await axios.post(`${appURL}/service/createBlog`, { value });
      if (res.data.success) {
        // 这里写成功后的逻辑,比如提示用户、跳转页面等
        console.log('博客创建成功');
      } else {
        // 处理创建失败的情况
        console.log('博客创建失败');
      }
    } catch (e) {
      console.error('提交出错了:', e);
    }
  };

  return (
    <div className='container'>
      <MDEditor
        className='reactEditorArea'
        value={value}
        onChange={handleChange}
      />
      {/* 添加提交按钮 */}
      <button onClick={handleSubmit}>提交博客</button>
    </div>
  );
};

export default YourComponent;

2. 若需实时提交(加防抖避免频繁请求)

如果业务确实需要在输入变化时提交,一定要加防抖,避免每输入一个字符就发一次请求,同时确保用最新的状态值:

import MDEditor from '@uiw/react-md-editor';
import axios from 'axios';
import { useEffect, useState } from 'react';

const YourComponent = () => {
  const [value, setValue] = useState("**Create a new blog**");

  const handleChange = (newValue) => {
    setValue(newValue);
  };

  // 监听value变化,防抖后提交
  useEffect(() => {
    // 500ms内没有新输入再提交,可根据需求调整时长
    const submitTimer = setTimeout(async () => {
      try {
        const res = await axios.post(`${appURL}/service/createBlog`, { value });
        if (res.data.success) {
          // 处理成功逻辑
        } else {
          // 处理失败逻辑
        }
      } catch (e) {
        console.error('提交出错:', e);
      }
    }, 500);

    // 组件卸载或value更新时清除定时器
    return () => clearTimeout(submitTimer);
  }, [value]);

  return (
    <div className='container'>
      <MDEditor
        className='reactEditorArea'
        value={value}
        onChange={handleChange}
      />
    </div>
  );
};

export default YourComponent;

3. 检查后端接收配置

如果前端传递的数据是完整的,但后端没收到全部内容,要确认后端是否正确配置了解析JSON请求体的中间件,比如Express框架要加express.json(),确保能正确读取req.body.value。


内容的提问来源于stack exchange,提问作者soccerway

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 16:20:37